How to sort data in mongo according to a value in key?
Answers
Answered by
0
You can achieve that using aggregation.
Make a new projection of the documents fields and add a temp marking field first: true if the createdByis abhi else first: falseSort by {first:-1, createdBy:1} to put your marked fields first in the sorted list(Re)Project your fields to remove the temp field first
code:
db.users.aggregate([ {$project: { first: { $cond: { if: { "$eq": ["$createdBy", 'abhi' ]}, then: true, else: false } }, createdBy: '$createdBy' } }, {$sort: {first:-1, "createdBy": 1}}, {$project: { createdBy: 1 // Don't include first:1 } } ])
Make a new projection of the documents fields and add a temp marking field first: true if the createdByis abhi else first: falseSort by {first:-1, createdBy:1} to put your marked fields first in the sorted list(Re)Project your fields to remove the temp field first
code:
db.users.aggregate([ {$project: { first: { $cond: { if: { "$eq": ["$createdBy", 'abhi' ]}, then: true, else: false } }, createdBy: '$createdBy' } }, {$sort: {first:-1, "createdBy": 1}}, {$project: { createdBy: 1 // Don't include first:1 } } ])
Similar questions