首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >结合$First和$last结果的Mongo

结合$First和$last结果的Mongo
EN

Stack Overflow用户
提问于 2018-04-24 14:50:54
回答 1查看 184关注 0票数 0

我有这样的数据集

代码语言:javascript
复制
{ "_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来实现它,但是我无法继续执行它。

目前,我从下面提到的查询中获得了这个输出:

代码语言:javascript
复制
db.restaurants.aggregate(    [      { $match: { "borough": "Manhattan"  } },     { $group: {_id: {borough:"$borough", cuisine: "$cuisine"}, count : { $sum : 1} } },  {$sort: {count:1,_id:1}}     ] );
EN

回答 1

Stack Overflow用户

发布于 2018-04-24 15:54:11

尝试以下聚合:

代码语言:javascript
复制
db.restaurants.aggregate([
    {
        $match: { "_id.borough": "Manhattan" }
    },
    {
        $sort: { RestaruntCount: 1 }
    },
    {
        $group: {
            _id: {borough:"$borough", cuisine: "$cuisine"},
            first: { $first: "$$ROOT" },
            last: { $last: "$$ROOT" }
        }
    }
])

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50004690

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档