【问题标题】:MongoDB aggregation pipeline: counting documents with a field is less than value?MongoDB聚合管道:使用字段计数文档小于值?
【发布时间】:2016-07-27 18:37:18
【问题描述】:

我有一个使用 MongoDB 聚合框架的现有报告,我想向其中添加一个新字段 - 一个数字字段小于给定值的所有文档的计数。

我的文档有一个长度字段,我已经在计算其平均值,所以除此之外,我还想要它低于某个特定数字的文档数。

我目前的聚合管道很简单:

db.streams.aggregate([ 
  { $match: { track_id: "ecb96af4537d4263b83f5675dbcc0388" }},
  { $group: { _id: "$source", listens: { $sum: 1 } }   }
])

我尝试过使用$sum$lt,但计数始终为0。我猜这是因为$sum 仅在返回1 时才计数,但$lt 返回true .这是我尝试过的:

db.streams.aggregate([{
  $match: {
    track_id: "ecb96af4537d4263b83f5675dadd0388"
  }
}, {
  $group: {
    _id: "$source",
    listens: {
      $sum: 1
    },
    skips: {
      $sum: {
        $lt: ["$length", 1000]
      }
    }
  }
}, ])

有谁知道我如何做到这一点?谢谢!

【问题讨论】:

    标签: mongodb aggregation-framework mongodb-aggregation


    【解决方案1】:

    你可以像这样添加一个嵌套条件

    ...
    skips: {
        $sum: {
            $cond: {
                if: { $lt: ["$length", 1000]},
                then: 1,
                else: 0
            }
        }
    }
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-10
      • 2018-06-02
      • 2023-02-11
      • 2018-08-06
      • 1970-01-01
      • 1970-01-01
      • 2019-01-17
      • 1970-01-01
      相关资源
      最近更新 更多