使用MongoDB聚合管道统计文档
这是我的源数据的简化版本:使用MongoDB聚合管道统计文档,mongodb,mapreduce,aggregation-framework,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 ca
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中,使用单个聚合管道是否可以做到这一点?是的,您可以使用$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
]
}
}
}
]);
是的,您可以使用$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
]
}
}
}
]);
有没有理由不使用
db.yourColl.find({Manual:true}).count()
和db.yourColl.find({Petrol:true}).count()
?有了相应的索引,这应该是一个实时查询…你是说这是一个更有效的方法吗?你能再解释一下吗?有没有理由不使用db.yourColl.find({Manual:true}).count()
和db.yourColl.find({Petrol:true}).count()
?有了相应的索引,这应该是一个实时查询…你是说这是一个更有效的方法吗?你能再解释一下吗?