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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 13:33:09  来源:igfitidea点击:

How to group query with multiple $cond?

mongodbaggregation-framework

提问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 $andoperatoris documented here: http://docs.mongodb.org/manual/reference/operator/aggregation/#boolean-operators

$and操作记录在这里:http://docs.mongodb.org/manual/reference/operator/aggregation/#boolean-operators