简体   繁体   中英

Mongodb distinct count for multi fields With example

I am using pymongo MongoClient to do multiple fields distinct count.

I found a similar example here: Link

But it doesn't works for me.

For example, by given:

data = [{"name": random.choice(all_names), 
         "value": random.randint(1, 1000)} for i in range(1000)]
collection.insert(data)

I want to count how many name, value combination. So I followed the Link above, and write this just for a test (I know this solution is not what I want, I just follow the pattern of the Link, and trying to get understand how it works, at least this code can returns me somthing):

collection.aggregate([
    {
        "$group": {
            "_id": {
                "name": "$name",
                "value": "$value",
                }
            }
    }, 
    {
        "$group": {
            "_id": {
                "name": "$_id.name",
                },
            "count": {"$sum": 1},
            },
    }
    ])

But the console gives me this:

on namespace test.$cmd failed: exception: A pipeline stage 
specification object must contain exactly one field.

So, what is the right code to do this? Thank you for all your helps.

Finally I found a solution: Group by Null

res = col.aggregate([
        {
            "$group": {
                "_id": {
                    "name": "$name",
                    "value": "$value",
                    },
                }
        }, 
        {
            "$group": {"_id": None, "count": {"$sum": 1}}
        },
        ])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM