someonewithakeyboardz1
someonewithakeyboardz1

Reputation: 167

Sorting MongoDB collection by same key with different values

I am trying to query my Mongo database to display all values from a certain collection, sorted by all the values of a certain key. For example, I have the collection:

{
  "id":"1235432",
  "name":"John Smith",
  "occupation":"janitor",
  "salary":"30000"
},
{
  "id":"23412312",
  "name":"Mathew Colins",
  "occupation":"janitor"
  "salary":"32000"
},
{
  "id":"7353452",
  "name":"Depp Jefferson",
  "occupation":"janitor"
  "salary":"33000"
},
{
  "id":"342434212",
  "name":"Clara Smith",
  "occupation":"Accountant",
  "salary":"45000"
},
{
  "id":"794563452",
  "name":"Jonathan Drako",
  "occupation":"Accountant",
  "salary":"46000"
},
{
  "id":"8383747",
  "name":"Simon Well",
  "occupation":"Accountant",
  "salary":"41000"
}

and I am trying to display only the TOP 2 with highest salary by occupation. My query looks something like this at the moment:

Stats.find({occupation:{$exists:true}}).populate('name').sort({salary:1}).limit(2)

by that only returns only 1 result instead of one from each occupation.

How can I change my query to display the top 2 of each occupation by salary range?

Upvotes: 1

Views: 107

Answers (1)

Nishant Bhardwaz
Nishant Bhardwaz

Reputation: 1001

You can use $aggregate as mentioned below.

 db.collectionName.aggregate({$match:{occupation:{$exists:true}}},
    { $sort: {"salary":-1}},
    { $limit: 2},
   { $project: {"name":1,"salary":1,_id:0} })

Output JSON:

{"name" : "Jonathan Drako",
"salary" : "46000"},
{"name" : "Clara Smith",
"salary" : "45000"}

Upvotes: 1

Related Questions