Mongo DB结合$ First和$ last结果

时间:2018-04-24 14:50:55

标签: mongodb mongodb-query

我有类似这样的数据集

{ "_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}}     ] );

1 个答案:

答案 0 :(得分:1)

尝试以下聚合:

db.restaurants.aggregate([
    {
        $match: { "_id.borough": "Manhattan" }
    },
    {
        $sort: { RestaruntCount: 1 }
    },
    {
        $group: {
            _id: {borough:"$borough", cuisine: "$cuisine"},
            first: { $first: "$$ROOT" },
            last: { $last: "$$ROOT" }
        }
    }
])

您可以使用特殊变量$$ROOT在聚合期间捕获整个文档。