So i have a list of posts data that look like this
[{user: 'Bob', country: 'USA'}
{user: 'Kim', country: 'Mexico'}
{user: 'Darren', country: 'Mexico'}
{user: 'Joe', country: 'Mexico'}]
etc....
I want my 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" } } },
]);
CodePudding user response:
$group
$addToSet
db.collection.aggregate([
{
"$group": {
"_id": "$country",
"users": {
"$addToSet": "$user"
}
}
}
])
result
[
{
"_id": "Mexico",
"users": [
"Kim",
"Darren",
"Joe",
"Bob"
]
},
{
"_id": "USA",
"users": [
"Bob"
]
}
]
CodePudding user response:
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"
}
}
})