Mongo 查询获取总计

Mongo query getting totals

如果我有一个看起来像这样的架构:

    var person = new Schema({
         active: {type: Boolean},
         otherSetting: {type: Boolean} 
    });

是否可以通过 一个 查询来获得所有人的总人数、活跃的总人数、不活跃的总人数以及有otherSetting 设置为 true 而 other Setting 设置为 false? otherSetting 和 active 是否必须分成两个查询?

我一直在研究这个问题的聚合框架,虽然这看起来是一个简单的问题,但我似乎无法只用一个查询来解决它。

这可能吗?感谢您的帮助。

这里的 aggregation framework has logical operators such as $cond 与您的布尔条件配合得很好:

db.collection.aggregate([
    { "$group": {
        "_id": null,
        "active": { "$sum": { "$cond": [ "$active", 1, 0 ] } },
        "inActive": { "$sum": { "$cond": [ "$active", 0, 1 ] } },
        "total": { "$sum": 1 }
    }}
])

$cond 运算符是一个 "ternary" 运算符 (if/then/else),它允许对 return true ( then ) 的逻辑条件进行评估或 false ( else ) 值。

"boolean" 在 $cond 的第一个参数中被评估为 true/false,它将适当的值传递给 $sum 以获得条件总计。

一切都在单个 $group 管道阶段中工作,分组键 _idnull,因为您想要将整个集合相加。如果根据另一个字段的值进行分组,则将 null 替换为您想要的字段。