mongodb 如何使用多个 $cond 对查询进行分组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20836978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to group query with multiple $cond?
提问by yountae.kang
I want to query like below, but this contains only one $cond
.
我想像下面这样查询,但这只包含一个$cond
.
How to query with two $cond
?
如何查询两个$cond
?
collection.aggregate(
{
$match : {
'_id' : {$in:ids}
}
},
{
$group: {
_id: '$someField',
...
count: {$sum: { $cond: [ { $eq: [ "$otherField", false] } , 1, 0 ] }}
}
},
function(err, result){
...
}
);
回答by Asya Kamsky
You want to use a compound expression inside {$cond:[]}
- something like:
您想在内部使用复合表达式{$cond:[]}
- 例如:
collection.aggregate(
{
$match : {
'_id' : {$in:ids}
}
},
{
$group: {
_id: '$someField',
...
count: {$sum: { $cond: [ {$and : [ { $eq: [ "$otherField", false] },
{ $eq: [ "$anotherField","value"] }
] },
1,
0 ] }}
}
},
function(err, result){
...
}
);
The $and
operatoris documented here: http://docs.mongodb.org/manual/reference/operator/aggregation/#boolean-operators
该$and
操作记录在这里:http://docs.mongodb.org/manual/reference/operator/aggregation/#boolean-operators