gpt4 book ai didi

mongodb - 如何在组内推送多个列的值

转载 作者:IT老高 更新时间:2023-10-28 13:34:33 26 4
gpt4 key购买 nike

看来我的查询不会像我预期的那样

我想按 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
}
},
])

最佳答案

您可以使用 $setUnion运算符(operator)。对于其他集合运算符,请阅读 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" ] }

关于mongodb - 如何在组内推送多个列的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29511299/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com