如何使用多个$ cond分组查询? [英] How to group query with multiple $cond?

查看:74
本文介绍了如何使用多个$ cond分组查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想像下面这样查询,但这只包含一个$cond.

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

如何用两个$cond查询?

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

推荐答案

您想在{$cond:[]}内部使用复合表达式-类似于:

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){
        ...
    }
);

记录了 $and运算符此处: http://docs.mongodb.org/manual/reference/运算符/聚合/#boolean-operators

这篇关于如何使用多个$ cond分组查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆