I have below set of user records, I need the results in such a way that logged in user(ObjectId("653222c20489664953bbaf1a") and status: Active) should come first then status: Pending users and finally rest of the status: Active users. How do I achieve this using mongo query?
{
"_id" : ObjectId("654b7348e704b8abba8af17e"),
"name": "",
"email" : "",
"status" : "Active"
},
{
"_id" : ObjectId("654b6c662f38d9e087086193"),
"name": "",
"email" : "",
"status" : "Pending"
},
{
"_id" : ObjectId("654b7fbae8392eddee2d1a31"),
"name": "",
"email" : "",
"status" : "Pending"
},
{
"_id" : ObjectId("653222c20489664953bbaf1a"),
"name": "",
"email" : "",
"status" : "Active"
},
{
"_id" : ObjectId("653269653bc13f1b96c6c37d"),
"name": "",
"email" : "",
"status" : "Active"
}
2
Answers
Solution 1:
$facet
– Allow to run multiple pipelines in a single query. Each pipeline contains the filter criteria that return different datasets.$project
– Decorate the output document. Combine the datasets from the previous stage into a single array.$unwind
– Deconstruct theusers
array.$replaceWith
– Replace the input document withusers
document.Demo Solution 1 @ Mongo Playground
Solution 2:
$set
– Addrank
field to assign the value based on criteria via$switch
.$match
– Remove the document withrank: -1
in case there is the document with the status other than "Pending" and "Active".$sort
– Sort by therank
field ascending.$unset
– Remove therank
field.Demo Solution 2 @ Mongo Playground
Add "sorting key" fields to your records, one for the exact match and one for the account status. Since 0 < 1, set those field values accordingly.
Mongo Playground, with the sort key fields present for clarity.
Result:
As an alternative, you could also nest the
else
condition in the first$cond
to use values 2 & 3 for account status and then sort on only one field.