英文:
How to add value in parent from each child array of object field in mongodb
问题
我无法在数组的每个元素上添加字段。
我使用mongodb 3.6,假设我在mongodb中有以下文档:
[
{
"_id": ObjectId("648fc2857edfa7ee4f1ce31c"),
"userId": "1",
"groups": [
{
"_id": ObjectId("648fc2857edfa7ee4f1ce31d"),
"groupId": "1",
"groupLeads": [
{
"userId": "4"
},
{
"userId": "5"
}
]
},
{
"_id": ObjectId("648fc2857edfa7ee4f1ce31d"),
"groupId": "2",
"groupLeads": [
{
"userId": "2"
},
{
"userId": "3"
}
]
}
]
}
]
我想在groups
数组下添加一个名为gLead
的字段,所以我使用了聚合函数来执行如下操作:
db.collection.aggregate([
{
"$addFields": {
"groups.gLead": {
"$map": {
"input": "$groups",
"as": "g",
"in": "$$g.groupLeads.userId"
}
}
}
}
])
为什么查询在第一个数组上返回如下结果:
{
"_id": ObjectId("648fc2857edfa7ee4f1ce31d"),
"gLead": [
[
"4",
"5"
],
[
"2",
"3"
]
],
"groupId": "1",
"groupLeads": [
{
"userId": "4"
},
{
"userId": "5"
}
]
}
而不是如下所示:
{
"_id": ObjectId("648fc2857edfa7ee4f1ce31d"),
"gLead": [ "4", "5" ],
"groupId": "1",
"groupLeads": [
{
"userId": "4"
},
{
"userId": "5"
}
]
}
我应该使用哪个聚合查询?
MongoDB游乐场链接:https://mongoplayground.net/p/xokkBwgRR2s
英文:
I cannot add the fields on each element in an array
I use mongodb 3.6, let say that I have a this documents in mongodb
[
{
"_id": ObjectId("648fc2857edfa7ee4f1ce31c"),
"userId": "1",
"groups": [
{
"_id": ObjectId("648fc2857edfa7ee4f1ce31d"),
"groupId": "1",
"groupLeads": [
{
"userId": "4"
},
{
"userId": "5"
}
]
},
{
"_id": ObjectId("648fc2857edfa7ee4f1ce31d"),
"groupId": "2",
"groupLeads": [
{
"userId": "2"
},
{
"userId": "3"
}
]
}
]
},
]
I want to add a field under the groups
array lets called gLead
so I use the aggregate function to do that like this
db.collection.aggregate([
{
"$addFields": {
"groups.gLead": {
"$map": {
"input": "$groups",
"as": "g",
"in": "$$g.groupLeads.userId"
}
}
}
}
])
why the query return like this on first array
{
"_id": ObjectId("648fc2857edfa7ee4f1ce31d"),
"gLead": [
[
"4",
"5"
],
[
"2",
"3"
]
],
"groupId": "1",
"groupLeads": [
{
"userId": "4"
},
{
"userId": "5"
}
]
},
instead of
{
"_id": ObjectId("648fc2857edfa7ee4f1ce31d"),
"gLead": [ "4", "5" ],
"groupId": "1",
"groupLeads": [
{
"userId": "4"
},
{
"userId": "5"
}
]
},
what query of aggregate should I use?
mongodb playground: https://mongoplayground.net/p/xokkBwgRR2s
答案1
得分: 1
你是否正在寻找一个能够将$map
处理后的信息与$mergeObject
合并在一起的管道?类似于这样:
db.collection.aggregate([
{
"$addFields": {
groups: {
"$map": {
"input": "$groups",
"as": "g",
"in": {
"$mergeObjects": [
"$$g",
{
gLead: "$$g.groupLeads.userId"
}
]
}
}
}
}
}
])
这个答案最初使用了$zip
,但输出格式不太正确
英文:
Are you looking for a pipeline that $mergeObject
s the $map
ped information together? Something like this:
db.collection.aggregate([
{
"$addFields": {
groups: {
"$map": {
"input": "$groups",
"as": "g",
"in": {
"$mergeObjects": [
"$$g",
{
gLead: "$$g.groupLeads.userId"
}
]
}
}
}
}
}
])
This answer originally used $zip
but the output format wasn't quite right
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论