[MongoDB daily records] The method of finding count (distinct a field) after group

Today, I encountered group后 count(distinct f1)a . Note: f1 represents a field

The general idea is: After grouping according to key1, find the unique number of field f1 in the group

1. mysql implementation

  • The pseudo-sql is as follows: (this is quite simple)
select key1, count(distinct f1) from t group by key1
复制代码

2. How does mongo implement it?

  • mongo is implemented as follows:
db.t.aggregate([
    {$match: {
        createTime: { $gte: 1, $lt: 8888888888888888 }
     }},
    {
        '$group': {
            "_id": {'key1':'$key1'},
            f1DistinctCount:{$addToSet:"$f1"},
            successCount: {
                $sum: {
                    $cond: [
                        {
                            $and: [
                                { $eq: ['$successOrFail', 1] }]
                        },
                        1,
                        0
                    ]
                }
            },
            failCount: {
                $sum: {
                    $cond: [
                        {$and: [
                              { $eq: ['$successOrFail', 0] }]
                        },
                        1,
                        0
                    ]

                }
            }
        },

    },
    {
        '$project': {
            '_id': 1, 'key1':1,'successCount': 1, 'failCount': 1,'f1DistinctCount':1
        }
    }
],{allowDiskUse: true});
复制代码

f1DistinctCount is a set collection. If you use mongotemplate, it is a com.mongodb.BasicDBList collection. Take out the length of the collection to get the result I want.

Of course, if you have a better way, you are welcome to exchange discussions and learn together.

Guess you like

Origin juejin.im/post/7078541935190736903
Recommended