问题
In our MongoDB document, we have two fields, organisationId and employeeId.
I want to show all the elements in a collection that have either of them matching the query parameters, so a basic OR.
One condition for Sorting is that I require is that the documents that have both the fields matching the query parameters should occur first, and then the documents matching organisationName parameter, next.
The idea is to show the data for the employee (i.e., you) first and then that of your organisation. (In our case topics suggested by you first and then by other employees in your organisation. As of now, I am using the following query to achieve this -
Campaigns.find({$and : [{'organisationName' : organisationName},{'employeeName' : userName}]},{}),
Campaigns.find({$and : [{'organisationName' : organisationName},{'employeeName' : {$ne : userName}}]},{})
But this does not seem like the most effective way to me. Any other query that can do this in just one call would be very nice, as that will help in the pagination too.
Thanks in advance
回答1:
This Aggregation query gets the desired result:
Input Documents:
{ "org" : "o1", "emp" : "e1", "data" : "1234" }
{ "org" : "o1", "emp" : "e2", "data" : "abcd" }
{ "org" : "o1", "emp" : "b3", "data" : "xyz" }
{ "org" : "o2", "emp" : "z3", "data" : "zzz" }
Query Parameters:
orgNameParam = "o1"
usrNameParam = "e2"
The Query:
db.orgemp.aggregate([
{ $match: { org: orgNameParam} },
{ $facet: {
firstQuery: [
{ $match: { emp: usrNameParam } }
],
secondQuery: [
{ $addFields: { isNotEmp: { $ne: [ "$emp", usrNameParam ] } } },
{ $match: { isNotEmp: true } },
{ $project: { isNotEmp: 0 } },
{ $sort: { emp: 1 } },
],
} },
{ $project: { result: { $concatArrays: [ "$firstQuery", "$secondQuery" ] } } },
])
The Result:
{
"result" : [
{
"_id" : ObjectId("5dc51432c2ac920e04692778"),
"org" : "o1",
"emp" : "e2",
"data" : "abcd"
},
{
"_id" : ObjectId("5dc51432c2ac920e04692779"),
"org" : "o1",
"emp" : "b3",
"data" : "xyz"
},
{
"_id" : ObjectId("5dc51432c2ac920e04692777"),
"org" : "o1",
"emp" : "e1",
"data" : "1234"
}
]
}
来源:https://stackoverflow.com/questions/58760718/mongodb-custom-sorting-on-two-fields