我的数据集类似
{ "_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}} ] );
尝试以下集合:
db.restaurants.aggregate([
{
$match: { "_id.borough": "Manhattan" }
},
{
$sort: { RestaruntCount: 1 }
},
{
$group: {
_id: {borough:"$borough", cuisine: "$cuisine"},
first: { $first: "$$ROOT" },
last: { $last: "$$ROOT" }
}
}
])
您可以使用特殊变量$$ROOT
在聚合期间捕获整个文档。