0

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

4
  • 2
    You can use $addToSet (docs.mongodb.com/manual/reference/operator/aggregation/addToSet) to get unique values. Commented Dec 26, 2018 at 7:30
  • where is the _id expression in the $group stage here? and what is the Text here? Commented Dec 26, 2018 at 7:46
  • @AnthonyWinzlet Updated the _id and Text is some text field Commented Dec 26, 2018 at 7:48
  • 2
    You can use $addToSet here, { "UNIQUE_TEXT": { "$addToSet": "YOUR_FIELD" }} and then use one $project stage to find the length of the UNIQUE_TEXT array or either use $facet aggregation Commented Dec 26, 2018 at 7:54

1 Answer 1

1

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
                    ]
                }
            }
}])
Sign up to request clarification or add additional context in comments.

1 Comment

Works Like a charm paired it up with a project stage and use $size to get the count

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.