按具有不同值的相同键对MongoDB集合进行排序

时间:2019-03-11 15:06:57

标签: mongodb sorting

我正在尝试查询Mongo数据库以显示某个集合中的所有值,并按某个键的所有值进行排序。例如,我有以下集合:

{
  "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"
}

,而我试图仅显示按职业划分薪水最高的 TOP 2 。目前,我的查询如下所示:

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

只能返回1个结果,而不是每个职业一个。

  

如何更改查询以按薪资范围显示每个职业的前2名?

1 个答案:

答案 0 :(得分:2)

您可以按如下所述使用$aggregate

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

输出JSON:

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