Reputation: 2034
I have a record fetched that I want to sort before sending to frontend.
db.getCollection('users').find({$or:
[
{createdBy: 'abhi'},
{createdBy: {'$ne': 'abhi'}, visibility: 'public'}
]}).sort({'createdBy': 1})
I want to sort all the records for createdBy user abhi first and then the other users.
Something like:
.sort({'createdBy == abhi': 1})
Upvotes: 4
Views: 3015
Reputation: 5529
You can achieve that using aggregation.
first: true
if the createdBy
is abhi
else first: false
{first:-1, createdBy:1}
to put your marked fields first in the sorted listfirst
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
}
}
])
Upvotes: 2