【问题标题】:Counting documents with MongoDB aggregation pipeline使用 MongoDB 聚合管道计算文档
【发布时间】:2014-08-08 15:19:31
【问题描述】:

这是我的源数据的简化版本:

Cars    | Manual     | Petrol
1       | true       | true
2       | true       | false
3       | true       | true
4       | true       | true
5       | false      | true
6       | false      | true

我正在尝试获取此输出:

Total cars: 6
Manual cars: 4
Petrol cars: 5

这在 MongoDB 中是否可以使用单个聚合管道?

【问题讨论】:

  • 不使用db.yourColl.find({Manual:true}).count()db.yourColl.find({Petrol:true}).count()有什么原因吗?有了相应的索引,这应该是一个实时查询...
  • 您是说这样做会更有效吗?你能再解释一下吗?

标签: mongodb mapreduce aggregation-framework


【解决方案1】:

是的,您可以使用 $group 聚合步骤和结合 $cond 的 $sum 运算符来做到这一点。

db.collection.aggregate([
     $group: {
         _id: null, // we want to group into a single document
         "Total Cars": { $sum: 1 }, // all documents
         "Manual Cars": { 
             $sum : { 
                // add a "1" when Manual is true, otherwise add a "0"
                $cond: [ { $eq: [ "$Manual", true ] }
                    1,
                    0
                ] 
            } 
         },
         "Petrol Cars": { 
             $sum : { 
                $cond: [ { $eq: [ "$Petrol", true ] }
                    1,
                    0
                ] 
            } 
         }
     }
]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-10
    • 1970-01-01
    • 1970-01-01
    • 2021-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多