'Mongoose and MongoDB - Get all countries and users associated with country
So I have a list of posts data that looks like this:
[
{user: 'Bob', country: 'USA'}
{user: 'Kim', country: 'Mexico'}
{user: 'Darren', country: 'Mexico'}
{user: 'Joe', country: 'Mexico'}
]
I want to get my data like:
[{Mexico: {'Kim', 'Darren', 'Joe'}, USA: {'Bob'}}]
This is what I got so far but I'm a bit confused by the docs and the posts here are pretty outdated. Any help would be greatly appreciated.
Post.aggregate([
{ $group: { _id: "$country", users: { $in: "$posts" } } },
]);
Solution 1:[1]
You're almost to the answer. You need $push
user
field to users
.
db.collection.aggregate({
$group: {
_id: "$country",
users: {
$push: "$user"
}
}
})
Sample Mongo Playground ($push
)
Use $addToSet
to add value to array without duplicate.
The $addToSet operator adds a value to an array unless the value is already present, in which case $addToSet does nothing to that array.
db.collection.aggregate({
$group: {
_id: "$country",
users: {
$addToSet: "$user"
}
}
})
Solution 2:[2]
$group
$addToSet
db.collection.aggregate([
{
"$group": {
"_id": "$country",
"users": {
"$addToSet": "$user"
}
}
}
])
result
[
{
"_id": "Mexico",
"users": [
"Kim",
"Darren",
"Joe",
"Bob"
]
},
{
"_id": "USA",
"users": [
"Bob"
]
}
]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |