Mongodb 结合$First和$last结果的Mongo DB
我有类似的东西Mongodb 结合$First和$last结果的Mongo DB,mongodb,mongodb-query,Mongodb,Mongodb Query,我有类似的东西 { "_id" : { "borough" : "Manhattan", "cuisine" : "Tex-Mex" }, "RestaruntCount" : 53 } { "_id" : { "borough" : "Manhattan", "cuisine" : "Bakery" }, "RestaruntCount" : 221 } { "_id" : { "borough" : "Manhattan", "cuisine" : "Soups & Sandwich
{ "_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
在聚合过程中捕获整个文档。谢谢您的回答,如果我不想搜索整个文档怎么办。假设自治区有多个值,对于每一组自治区,我需要找到最大值和最小值。我需要应用于给定的分组,而不是整个文档?@FabTrex只是为了澄清,你能给我展示一下预期结果吗?{u id:{“borough”:“Manhattan”,“courine”:“Bakery”},“RestaruntCount”:221}{u id:{“borough”:“Manhattan”,“courine”:“Nuts/糖果”},“RestaruntCount”:4}{{u id:{“borough”:“布鲁克林”、“美食”:“越南/柬埔寨/马来西亚”},“餐馆帐户”:40}{“自治区”:“布鲁克林”、“美食”:“菲律宾人”},“餐馆帐户”:5}{“自治区”:“纽约”,“美食”:“印度”},“餐馆帐户”:5}{“自治区”:“纽约”,“美食”:“中国”},“餐馆帐户”:1}像这样的……最高和最低的餐厅数量都是以街区和cusinetype为单位的wise@FabTrex我不确定我是否理解正确,但我认为您必须使用{borough:$borough],coineering:$coineering}
作为分组id。