How to group query with multiple $cond?

天涯浪子 提交于 2019-12-20 09:33:47

问题


I want to query like below, but this contains only one $cond.

How to query with two $cond?

collection.aggregate(
    { 
        $match : { 
            '_id' : {$in:ids}
        } 
    },
    {
        $group: {
            _id: '$someField',
            ...
            count: {$sum: { $cond: [ { $eq: [ "$otherField", false] } , 1, 0 ] }}
        }
    },
    function(err, result){
        ...
    }
);

回答1:


You want to use a compound expression inside {$cond:[]} - something like:

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



来源:https://stackoverflow.com/questions/20836978/how-to-group-query-with-multiple-cond

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!