Этот запрос агрегации получает желаемый результат:
Входные документы:
{ "org" : "o1", "emp" : "e1", "data" : "1234" }
{ "org" : "o1", "emp" : "e2", "data" : "abcd" }
{ "org" : "o1", "emp" : "b3", "data" : "xyz" }
{ "org" : "o2", "emp" : "z3", "data" : "zzz" }
Параметры запроса:
orgNameParam = "o1"
usrNameParam = "e2"
Запрос:
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" ] } } },
])
Результат:
{
"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"
}
]
}