在mongo DB中,如何在单个查询中获取多个计数?

时间:2018-08-13 20:08:15

标签: database mongodb mongodb-query aggregation-framework nosql-aggregation

由于我无法控制的原因,我目前正尝试从mLab API中提取计数。因此,我想在一个查询中从那里获取所需的数据,以便可以限制API调用的数量。

假设我的数据如下:

{
"_id": {
    "$oid": "12345"
},
"dancer": "Beginner",
"pirate": "Advanced",
"chef": "Mid",
"beartamer": "Mid",
"swordsman": "Mid",
"total": "Mid"
}

我知道我可以用类似的方法进行6次查询:

db.score.aggregate({"$group": { _id: {"total":"$total"}, count: {$sum:1} }} )

但是如何查询以获得每个键的计数?我想看看类似的东西:

{ "_id" : { "total" : "Advanced" }, "count" : 1 }
{ "_id" : { "total" : "Mid" }, "count" : 1 }
{ "_id" : { "total" : "Beginner" }, "count" : 4 }
{ "_id" : { "pirate" : "Advanced" }, "count" : 1 }
//...etc

1 个答案:

答案 0 :(得分:2)

以下内容应为您提供所需的确切信息:

db.scores.aggregate({
    $project: {
        "_id": 0 // get rid of the "_id" field since we do not want to count it
    }
}, {
    $project: {
        "doc": {
            $objectToArray: "$$ROOT" // transform all documents into key-value pairs
        }
    }
}, {
    $unwind: "$doc" // flatten the resulting array into separate documents
}, {
    $group: {
        "_id": "$doc", // group by distinct key-value combination
        "count": { $sum: 1 } // count documents per bucket
    }
}, {
    $project: {
        "_id": { // some more transformation magic to recreate the desired output structure
            $mergeObjects: [
                { $arrayToObject: [ [ "$_id" ] ] },
                { "count": "$count" }
            ]
        },
    }
}, {
    $replaceRoot: {
        "newRoot": "$_id" // this moves the contents of the "_id" field to the root of the documents
    }
})