MongoDB Custom sorting on two fields

荒凉一梦 提交于 2020-01-14 05:35:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!