Boas Enkler
Boas Enkler

Reputation: 12557

MongoDB aggregation running two group operations at once

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.

Upvotes: 1

Views: 39

Answers (1)

DAXaholic
DAXaholic

Reputation: 35408

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')

Upvotes: 1

Related Questions