MongoDB。从新字段中的数组中获取每个元素
MongoDB. Get every element from array in new field
我有一个包含嵌套数组的文档 array_field:
{
"_id": {
"$oid": "1"
},
"id": "1",
"array_field": [
{
"data": [
{
"regions": [
{
"result": {
"item": [
"4",
"5",
"3"
]
}
},
{
"result": {
"item": [
"5"
]
}
},
{
"result": {
"item": [
"1"
]
}
}
]
}
]
}
]
}
我需要添加新字段,例如 new_added_field,每个数组元素来自 array_field.data.regions.result.item 并从文档中删除 array_field。
例如:
{
"_id": {
"$oid": "1"
},
"id": "1",
"new_added_field": [4,5,3,5,1]
}
我想我可以在 $unwind 或 $map 的帮助下做到这一点,但是有困难并且需要圆顶提示,我如何通过 help op aggregation 来做到这一点?
如你所说,
db.collection.aggregate([
{
"$project": {
newField: {
"$map": {
"input": "$array_field",
"as": "m",
"in": "$$m.data.regions.result.item"
}
}
},
},
{ "$unwind": "$newField" },
{ "$unwind": "$newField" },
{ "$unwind": "$newField" },
{ "$unwind": "$newField" },
{
"$group": {
"_id": "$_id",
"newField": { "$push": "$newField" }
}
}
])
我有一个包含嵌套数组的文档 array_field:
{
"_id": {
"$oid": "1"
},
"id": "1",
"array_field": [
{
"data": [
{
"regions": [
{
"result": {
"item": [
"4",
"5",
"3"
]
}
},
{
"result": {
"item": [
"5"
]
}
},
{
"result": {
"item": [
"1"
]
}
}
]
}
]
}
]
}
我需要添加新字段,例如 new_added_field,每个数组元素来自 array_field.data.regions.result.item 并从文档中删除 array_field。
例如:
{
"_id": {
"$oid": "1"
},
"id": "1",
"new_added_field": [4,5,3,5,1]
}
我想我可以在 $unwind 或 $map 的帮助下做到这一点,但是有困难并且需要圆顶提示,我如何通过 help op aggregation 来做到这一点?
如你所说,
db.collection.aggregate([
{
"$project": {
newField: {
"$map": {
"input": "$array_field",
"as": "m",
"in": "$$m.data.regions.result.item"
}
}
},
},
{ "$unwind": "$newField" },
{ "$unwind": "$newField" },
{ "$unwind": "$newField" },
{ "$unwind": "$newField" },
{
"$group": {
"_id": "$_id",
"newField": { "$push": "$newField" }
}
}
])