【问题标题】:Return a document with the max value on a number field using MongoDB aggregation使用 MongoDB 聚合返回具有数字字段最大值的文档
【发布时间】:2015-01-04 19:56:56
【问题描述】:

例如,如果我有一堆文件

{
  _id: mongoId,
  subcatId: mongoId,
  viewCount: 2
}

_id 是唯一的,但 subcatId 不是。

如果我想返回每个 subcatId 具有最高 viewCount 的每个文档,我将如何使用 Mongoose/MongoDB 的聚合来做到这一点?

【问题讨论】:

    标签: mongodb mongoose aggregation-framework


    【解决方案1】:

    你可以这样做:

    db.test.aggregate([
      // Sort the docs by viewCount descending so that the highest ones come first
      {$sort: {viewCount: -1}},
      // Group by subcatId and take the first doc from each group
      {$group: {_id: '$subcatId', doc: {$first: '$$ROOT'}}}
    ])
    

    $$ROOT 系统变量是在 2.6 中添加的,它表示在管道中该阶段正在处理的整个文档。所有系统变量都以$$ 前缀引用。

    对于旧版本的 MongoDB,您需要将您需要的每个字段单独添加到 $group

    db.test.aggregate([
      {$sort: {viewCount: -1}},
      {$group: {
        _id: '$subcatId', 
        doc_id: {$first: '$_id'},
        viewCount: {$first: '$viewCount'}
      }}
    ])
    

    【讨论】:

    • “$$ROOT”到底是什么我很难找到与该术语相关的文档。
    • 我收到此错误未捕获异常:聚合失败:{“errmsg”:“异常:FieldPath 字段名称可能不以'$'开头。”,“代码”:16410,“确定”:0 } 你也可能想包括:在 $group 旁边
    • @AustinDavis $$ROOT 是在 MongoDB 2.6 中添加的,因此如果您运行的是旧版本,则必须将每个字段单独包含在 $group 中。
    • 是的,我使用的是 2.4.11 :( 所以如果我还想在返回中包含文档 _id 和 viewCount 你会如何建议这样做?
    猜你喜欢
    • 2014-12-12
    • 1970-01-01
    • 2013-05-06
    • 1970-01-01
    • 1970-01-01
    • 2016-05-14
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多