Mongodb 复杂的$sum查询

Mongodb 复杂的$sum查询,mongodb,mongodb-query,aggregation-framework,Mongodb,Mongodb Query,Aggregation Framework,我正在使用Kettle,需要计算有多少条目具有某些期望值(内部数组中至少有两个字段) 例如: { "_id":"HY1406", "accounts": [ { "should_exist" : 1, "endpoint" : "0_AD", "exists" : 0, "short_login" : "TB6" }, {

我正在使用Kettle,需要计算有多少条目具有某些期望值(内部数组中至少有两个字段)

例如:

{
    "_id":"HY1406",
    "accounts": [ 
        {
            "should_exist" : 1,
            "endpoint" : "0_AD",
            "exists" : 0,
            "short_login" : "TB6"
        },
        {
            "should_exist" : 1,
            "endpoint" : "0_AD",
            "exists" : 0,
            "short_login" : "TB7"
        },
        {
            "should_exist" : 1,
            "endpoint" : "0_AD",
            "exists" : 0,
            "short_login" : "TB8"
        }
    ]
}
我必须计算一个帐户中至少有多少文档具有
“sould_exist”=1和“exists”=0


如何使用MongoDB查询执行此操作?

您需要使用
$elemMatch
来匹配数组中嵌入文档的两个条件。使用
find()
获取光标并调用
count()

或者将您的筛选器写入
count()

或者加总

db.collection.aggregate([
{
    $match : {
        accounts : {
            $elemMatch : {should_exist : 1, exists : 0}
        }
    }
},
{
    $group : {
        _id : "foo",
        count : {$sum : 1}
    }
}
])

预期的结果是什么?向我们显示代码,您已经尝试过的代码。db.collection.find({“accounts.should_exist”:1,“accounts.exists”:0})。count()@mmu36478,我们可以使用聚合吗?@Styvane:我正在查找accounts字段中至少有一个条目“sould_exist”=1和“exists”的所有文档的数量=0这似乎很有趣,实际上,我想计算两个类别的总和:类别1:“应该存在”=1和“存在”=0,类别2:“应该存在”=1和“存在”=1。结果是:{“_id”:1.0,“numCat1”:2,“numCat2”:7}我如何进行这样的查询?这与您在问题中发布的内容完全不同。我必须计算有多少文档至少有一个帐户“sould_exist”=1,“exists”=0。
db.collection.count({
    accounts : {
        $elemMatch : {should_exist : 1, exists : 0}
    }
})
db.collection.aggregate([
{
    $match : {
        accounts : {
            $elemMatch : {should_exist : 1, exists : 0}
        }
    }
},
{
    $group : {
        _id : "foo",
        count : {$sum : 1}
    }
}
])