在mongodb中查找具有计数和最高顺序限制的独特嵌套数据

时间:2018-08-06 10:56:56

标签: node.js mongodb mongoose

我只想查找5条具有唯一数据的最高记录,我在下面使用:

db.collection.aggregate(
{$unwind: '$restaurantcompetitors'},
{$unwind: '$restaurantcompetitors.competitorName'},
{$group: {_id: '$restaurantcompetitors.competitorName', count:{$sum:1}}}

我得到的结果如下:

{ "_id" : "Platterz.co", "count" : 1 }
{ "_id" : "ChowNow", "count" : 3 }
{ "_id" : "cater2.me", "count" : 1 }
{ "_id" : "App-App.co", "count" : 1 }
{ "_id" : "airportsherpa.io", "count" : 1 }
{ "_id" : "Eat24", "count" : 4 }
{ "_id" : "Chowbus", "count" : 5 }

但是我想要:

{ "_id" : "Chowbus", "count" : 5 }
{ "_id" : "Eat24", "count" : 4 }
{ "_id" : "ChowNow", "count" : 3 }

预先感谢

1 个答案:

答案 0 :(得分:1)

使用$sort进行计数,然后使用$limit

db.collection.aggregate(
  { '$unwind': '$restaurantcompetitors' },
  { '$unwind': '$restaurantcompetitors.competitorName' },
  { '$group': {
    '_id': '$restaurantcompetitors.competitorName',
    'count': { '$sum': 1    }
  }},
  { '$sort': { 'count': -1 }},
  { '$limit': 3 },
)