1

Given:

A collection where I have some columns where for two of them I want to get all used values

Currently I'm doing two aggregations like below (simplified)

db['myCollection'].aggregate(
  [{$group: {"_id":"$firstCol"}}  ]
);

and

db['myCollection'].aggregate(
  [{$group: {"_id":"$secondCol"}}  ]
);

But it feels like a waste of resources to run two aggregations. Is there a way to get both grouped results at once?

I thought about combining them and later on split it in code.

1
  • It is unclear what you are asking here. Do you want to group by "firstCol" and "secondCol"? Can you provide sample document with the expected result? Commented Jul 14, 2016 at 8:32

1 Answer 1

1

You could do it like so with the aid of the $addToSet operator

db['myCollection'].aggregate([
    {
        $group: {
            _id: null,
            col1: {
                $addToSet: "$firstCol"
            },
            col2: {
                $addToSet: "$secondCol"
            }
        }
    }
])

If you have indexes on the target fields then I would choose separate calls with distinct, as this can take advantage of those and probably result in less workload / faster execution times.

db[myCollection].distinct('firstCol')
Sign up to request clarification or add additional context in comments.

1 Comment

@BoasEnkler Did this answer help or do you need something different?

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.