MongoDB-如何从非结构化数组字段列表中重命名特定字段?
我有几个文件,如下所示。现在,我需要重命名 middlename 字段中
{
"id":"abc",
"name":[
{
"first_name":"abc",
"last_name":"def"
},
{
"first_name":"ghi",
"last_name":"mno",
"middilename":"xyz"
}
]
}
这是我希望的。
{
"id":"abc",
"name":[
{
"first_name":"abc",
"last_name":"def"
},
{
"first_name":"ghi",
"last_name":"mno",
"mid_name":"xyz"
}
]
}
这就是我所做的,但会引发错误。
db.md_carrierInformation.updateMany({"name.middlename":{$exists:true}}, {$rename:{"name.$.middlename":"name.mid_name"}})
错误
mongoservererror:$重命名的源字段可能不动态:name。$。middlename
I have several documents as given below. Now I need to do rename the middlename field into mid_name if middlename exists in the document.
{
"id":"abc",
"name":[
{
"first_name":"abc",
"last_name":"def"
},
{
"first_name":"ghi",
"last_name":"mno",
"middilename":"xyz"
}
]
}
This is something that I expect it to be.
{
"id":"abc",
"name":[
{
"first_name":"abc",
"last_name":"def"
},
{
"first_name":"ghi",
"last_name":"mno",
"mid_name":"xyz"
}
]
}
And this is what I have done but it throws the error.
db.md_carrierInformation.updateMany({"name.middlename":{$exists:true}}, {$rename:{"name.$.middlename":"name.mid_name"}})
ERROR
MongoServerError: The source field for $rename may not be dynamic: name.$.middlename
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用聚合管道进行更新。
$ set
- set <代码>名称数组字段。1.1。
$ MAP
- 迭代名称>名称>数组中的每个项目并返回新数组。
1.2。
$ cond
- 检查当前文档的middlename
的条件。1.2.1。如果
true
,则将当前文档与字段mid_name
通过$ mergeObjects
。。
1.2.2。如果
false
,请保留现有文档。$ unset
- 删除name.middlename
的字段。示例mongo playground
Work on the update with the aggregation pipeline.
$set
- Setname
array field.1.1.
$map
- Iterate each item inname
array and return new array.1.2.
$cond
- Condition for checking current document'smiddlename
is not existed.1.2.1. If
true
, with merge current document with the document with fieldmid_name
via$mergeObjects
.1.2.2. If
false
, remain the existing document.$unset
- Remove field forname.middlename
.Sample Mongo Playground