Abhishek
Abhishek

Reputation: 2034

Mongodb: Sort a list by key and value

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

Answers (1)

sergiuz
sergiuz

Reputation: 5529

You can achieve that using aggregation.

  1. Make a new projection of the documents fields and add a temp marking field first: true if the createdBy is abhi else first: false
  2. Sort by {first:-1, createdBy:1} to put your marked fields first in the sorted list
  3. (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
        }       
    }
])

Upvotes: 2

Related Questions