Reputation: 505
I am creating a search form for users in my mongo database having this structure
[
{ _id: 45aba8a34a8a,
name: blabla,
country: france,
region: alsace
},
{ _id: 6ccbef3a4a83,
name: blabla,
country: germany,
region: hessen
}
]
What I am trying to achieve is to get a list of possible countries and regions in the database. I can partly achieve this by the following code
collection.aggregate([
{
$group: {
_id: "$country"
}
}
], function (err, res) {
...
});
However this will only give me the grouped countries and not regions. Is there a way to do this in a single aggregation? I guess the ideal result would be something like
{
countries: [ 'france', 'germany', ... ],
regions: [ 'alsace', 'hessen', ...]
}
But I haven't been able to find how to obtain this anywhere on the net.
Upvotes: 0
Views: 32
Reputation: 2354
You should try something like below.
collection.aggregate([
{
$group: {
_id: { country: "$country", region: "$region" }
}
}
], function (err, res) {
...
});
You may look at $addToSet in case you need distinct records.
Upvotes: 1