Bhavani Ravi
Bhavani Ravi

Reputation: 2291

count and count unique in a single mongo aggregate query

I have a mongo aggregate query which calculates COUNT, MIN, MAX and BLANK counts of different keys.

db.getCollection('ReportTestProcess').aggregate([
   $group": {
                "_id":0,
                "Inititated_on_MIN": {
                    "$min": "$Inititated_on.v"
                },
                "Inititated_on_MAX": {
                    "$max": "$Inititated_on.v"
                },
                "Text_COUNT":{$sum:1},
                "Text_BLANK": {
                    "$sum": {
                        "$cond": [
                            {
                                "$ifNull": [
                                    "$Inititated_on.v",
                                    false
                                ]
                            },
                            0,
                            1
                        ]
                    }
                }
}])

Now I want UNIQUE_COUNT of elements along with it. The only way I could think of doing it is to group based the fields but grouping will affect the results of MIN, MAX or COUNT

Upvotes: 0

Views: 143

Answers (1)

Ravi Kumar Gupta
Ravi Kumar Gupta

Reputation: 1798

You can use $addToSet

Sets always keep unique values. Your code should look like.

db.getCollection('ReportTestProcess').aggregate([
   $group": {
            "Inititated_on_MIN": {
                "$min": "$Inititated_on.v"
            },
            "Inititated_on_MAX": {
                "$max": "$Inititated_on.v"
            },
            "Text_COUNT":{$sum:1},
            "Text_UNIQUE": { $addToSet: "$Inititated_on.v" }
            "Text_BLANK": {
                "$sum": {
                    "$cond": [
                        {
                            "$ifNull": [
                                "$Inititated_on.v",
                                false
                            ]
                        },
                        0,
                        1
                    ]
                }
            }
}])

Upvotes: 1

Related Questions