我只想查找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 }
预先感谢
答案 0 :(得分:1)
使用$sort
进行计数,然后使用$limit
db.collection.aggregate(
{ '$unwind': '$restaurantcompetitors' },
{ '$unwind': '$restaurantcompetitors.competitorName' },
{ '$group': {
'_id': '$restaurantcompetitors.competitorName',
'count': { '$sum': 1 }
}},
{ '$sort': { 'count': -1 }},
{ '$limit': 3 },
)