使用MongoDB聚合管道计算文档

时间:2014-08-08 15:19:32

标签: mongodb mapreduce aggregation-framework

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

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中实现吗?

1 个答案:

答案 0 :(得分:4)

是的,您可以使用$ group聚合步骤和$ sum运算符结合$ cond执行此操作。

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