mongodb-如何更新嵌套数组元素的特定属性
我有一个带有以下结构的集合:
{
arrangements: [
{ displayName: "MRT.8" },
{ displayName: "MRT.10" },
{ displayName: "MRT.12" },
(...)
]
}
我希望substring MRT
被用 Mobile
替换,因此结果将如下:
{
arrangements: [
{ displayName: "MOBILE.8" },
{ displayName: "MOBILE.10" },
{ displayName: "MOBILE.12" },
(...)
]
}
plost 在SO 上解决类似问题的解决方案,我做了以下操作:
db.collection('releaseDocument').updateMany({"arrangements.displayName": {$regex: /MRT\..*/}}, [
{
$set: {
'arrangements.displayName': {
$concat: [
"MOBILE.",
{$arrayElemAt: [{$split: ["$displayName", "MRT."]}, 0]}
]
}
}
}
])
但这是不起作用的:因为<代码> $ 是指当前文档,而不是嵌套数组元素。我该如何实现我上面描述的内容?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看来您正在使用Contregation Pipeline进行更新,需要
$ MAP
操作员。对于
$ arrayelementat
零件,我认为您需要1作为索引来获取第二个元素。假设过滤器返回要更新的文档:
示例mongo Playground
Seems you are working with Update with Aggregation Pipeline, you need
$map
operator.For
$arrayElementAt
part, I think you need 1 as an index to take the second element.Assume that the filter returns documents to be updated:
Sample Mongo Playground