It seems my query will won't act as my expect
I want to group by name
and mapping location1 and location2 into an array called locations
{name: "Jack", localtion1: "Taiwan", localtion2: "France"},
{name: "Jack", localtion1: "Japan", localtion2: "Taiwan"},
{name: "Mary", localtion1: "China", localtion2: "Taiwan"}
{
name: "Jack",
localtions: ["Taiwan", "France", "Japan"]
},
{name: "Mary", localtions: ["China", "Taiwan"]}
db.collection.aggregate([
{
$group: {
_id: "$name",
"localtions":{
$addToSet: "$localtion1"
},
"localtions":{
$addToSet: "$localtion2"
}
count: { $sum: 1 }
}
},
{
$project: {
name: "$_id",
localtions: "$localtions",
_id: 0
}
},
])
You can use the $setUnion
operator. For others set operators read this.
db.collection.aggregate([
{
"$group": {
"_id": "$name",
"localtion1": { "$addToSet": "$localtion1" },
"localtion2": { "$addToSet": "$localtion2" }
}
},
{
"$project": {
"name": "$_id",
"localtions": { "$setUnion": [ "$localtion1", "$localtion2" ] },
"_id": 0
}
}
])
Output
{ "name" : "Mary", "localtions" : [ "Taiwan", "China" ] }
{ "name" : "Jack", "localtions" : [ "France", "Japan", "Taiwan" ] }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With