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

时间:2022-10-09 19:42:56

I'm currently trying to massage out counts from the mLab API for reasons I don't have control over. So I want to grab the data I need from there in one query so I can limit the amount of API calls.

我目前正试图从mLab API中按下计数,原因是我无法控制。所以我想在一个查询中从那里获取我需要的数据,这样我就可以限制API调用的数量。

Assuming that my data looks like this:

假设我的数据如下所示:

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

I know I can do 6 queries with something similar to:

我知道我可以用以下类似的东西做6个查询:

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

but how do I query to get the count for each key? I'd like to see something akin to:

但是如何查询以获取每个键的计数?我想看到类似于:

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

1 个解决方案

#1


2  

The following should give you precisely what you want:

以下内容应该准确地给你你想要的东西:

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
    }
})

#1


2  

The following should give you precisely what you want:

以下内容应该准确地给你你想要的东西:

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
    }
})