How to use Conditional Statements for sorting data in MongoDB
Posted By : Pankaj Kumar Yadav | 29-Jun-2016
Suppose we have a document User in mongodb with following data.
{ id:1, name: "Jack" status:"VERIFIED" }, { id:2, name: "Alex" status:"NOT_VERIFIED" }, { id:3, name: "John" status:"NOT_VERIFIED" }, { id:4, name: "Anna" status:"NOT_VERIFIED" }, { id:5, name: "Snajay" status:"VERIFIED" }
now I need to sort it like --
1) Sort all user by name in ascending order if status is "VERIFIED".
2) Sort all user by id in ascending order if status is "NOT_VERIFIED"
Here is mongo query to sort user according to above condition.
db.user.aggregate([ { $project: { id: 1, name: 1, status: 1, sort: { $cond: { if: { $eq: ["$status", "VERIFIED"] }, then: "$name", else: "$id" } } } }, { $sort: { sort: 1 } } ])
It will return -- {id:1, name: "Jack" status:"VERIFIED", sort: "Jack" }, { id:5, name: "Snajay" status:"VERIFIED", sort: "Snajay" }, { id:2, name: "Alex" status:"NOT_VERIFIED", sort: "2" }, { id:3, name: "John" status:"NOT_VERIFIED", sort: "2" }, { id:4, name: "Anna" status:"NOT_VERIFIED", sort: "2" }
This is sorted result as we need.
Thanks
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Pankaj Kumar Yadav
Pankaj has been working as a Grails developer expertise in struts, spring, ejb, hibernate and angularjs framework.