似乎我的查询不会像我期望的那样
我希望按name
进行分组,并将location1和location2映射到名为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
}
},
])
答案 0 :(得分:7)
您可以使用$setUnion
运算符。对于其他设置运算符,请阅读this。
db.collection.aggregate([
{
"$group": {
"_id": "$name",
"localtion1": { "$addToSet": "$localtion1" },
"localtion2": { "$addToSet": "$localtion2" }
}
},
{
"$project": {
"name": "$_id",
"localtions": { "$setUnion": [ "$localtion1", "$localtion2" ] },
"_id": 0
}
}
])
<强>输出强>
{ "name" : "Mary", "localtions" : [ "Taiwan", "China" ] }
{ "name" : "Jack", "localtions" : [ "France", "Japan", "Taiwan" ] }
答案 1 :(得分:1)
您还可以在 $project
管道中使用$setUnion
运算符,如下所示:
db.collection.aggregate([
{
"$group": {
"_id": "$name",
"location1": {
"$addToSet": "$localtion1"
},
"location2": {
"$addToSet": "$localtion2"
}
}
},
{
"$project": {
"name": "$_id",
"locations": {
"$setUnion": [ "$location1", "$location2" ]
},
"_id": 0
}
}
])
会给你结果:
/* 0 */
{
"result" : [
{
"name" : "Mary",
"locations" : [
"China",
"Taiwan"
]
},
{
"name" : "Jack",
"locations" : [
"Japan",
"Taiwan",
"France"
]
}
],
"ok" : 1
}