简体   繁体   中英

How to do distinct and group in MongoDB Aggregation Framework?

I have a collection in MongoDB with such data:

sid; geo
--------
4; 100
4; 101
2; 100
2; 106
2; 107
1; 100
1; 100
1; 100
1; 110
1; 100

How to do such SQL query in MongoDB?

SELECT sid COUNT(DISTINCT geo) FROM sites GROUP BY sid

I want to have a collection with count of unique geo for every sid:

sid; geo_count
--------------
4; 2
2; 3
1; 2

Since DISTINCT is actually a type of group you can do:

db.c.aggregate({
    {$group: {_id: '$geo', sid: '$sid', 'geo_sum': {$sum: 1}}},
    {$group: {_id: '$sid', 'geo_count': {$sum: 1}}}
})

Distinct is a type of grouping indeed but the output equivalent of that type of query is this:

db.collection.aggregate([
    { "$group": {
        "_id": { "sid": "$sid", "geo": "$geo" }
    }},
    { "$group": {
        "_id": "$_id.sid",
        "geo_count": { "$sum": 1 }
    }}
]}

So you need to first group to get the "distinct" results of "geo" within "sid". Then you count the number of distinct results.

If I understand your question correctly, you should be able to achieve that by doing another:

$group

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