我有这样的数据集
{ "_id" : { "borough" : "Manhattan", "cuisine" : "Tex-Mex" }, "RestaruntCount" : 53 }
{ "_id" : { "borough" : "Manhattan", "cuisine" : "Bakery" }, "RestaruntCount" : 221 }
{ "_id" : { "borough" : "Manhattan", "cuisine" : "Soups & Sandwiches" }, "RestaruntCount" : 44 }
{ "_id" : { "borough" : "Manhattan", "cuisine" : "Vietnamese/Cambodian/Malaysia" }, "RestaruntCount" : 38 }
{ "_id" : { "borough" : "Manhattan", "cuisine" : "Filipino" }, "RestaruntCount" : 5 }
{ "_id" : { "borough" : "Manhattan", "cuisine" : "Egyptian" }, "RestaruntCount" : 5 }
{ "_id" : { "borough" : "Manhattan", "cuisine" : "Nuts/Confectionary" }, "RestaruntCount" : 4 }从这个数据集,我需要得到最高和最低的美食类型的数量在曼哈顿区。我知道我需要使用$first和$last来实现它,但是我无法继续执行它。
目前,我从下面提到的查询中获得了这个输出:
db.restaurants.aggregate( [ { $match: { "borough": "Manhattan" } }, { $group: {_id: {borough:"$borough", cuisine: "$cuisine"}, count : { $sum : 1} } }, {$sort: {count:1,_id:1}} ] );发布于 2018-04-24 15:54:11
尝试以下聚合:
db.restaurants.aggregate([
{
$match: { "_id.borough": "Manhattan" }
},
{
$sort: { RestaruntCount: 1 }
},
{
$group: {
_id: {borough:"$borough", cuisine: "$cuisine"},
first: { $first: "$$ROOT" },
last: { $last: "$$ROOT" }
}
}
])您可以使用特殊变量$$ROOT在聚合期间捕获整个文档。
https://stackoverflow.com/questions/50004690
复制相似问题