[英]Update one or two fields in an array for all documents in a collection - mongo db
首先,我使用的是 Mongo DB Compass 和 mongo shell。 我想更新例如这个字段:1List.Comment
在此字段中,我想将 'ß' 替换为 'ss'
1List 是一个数组。 在这个数组中我可以有几个对象。 这些对象包含“评论”字段。
这是一个示例文档:
{
"_id":{
"$oid":"12345"
},
"1List":[
{
"Comment": "TEßT Comment",
"TEXT_VALUE":"Another test string",
"REASON":"No Reason"
},
{
"Comment": "TEßT Comment the second",
"TEXT_VALUE":"Another second string",
"REASON":"No Reason again"
}
]
}
这是我在 mongo db shell 中尝试过的:
db.getCollection('TEST_Collection').aggregate(
[{
$match: {
'1List.Comment': {
$exists: true
}
}
}, {
$unwind: {
path: '$1List',
includeArrayIndex: '1List.CommentArrayIndex',
preserveNullAndEmptyArrays: false
}
}, {
$project: {
'1List.Comment': 1
}
}]
)
.forEach(function(doc,Index) {doc.1List.Comment=doc.1List.Comment.replace(/[ß]/g, 'ss');
db.TEST_Collection.updateMany({ "_id": doc._id },{ "$set": { "1List.Comment": doc.1List.Comment } });})
但我收到错误消息:无法在元素 {1List:....... 中创建字段“评论”
任何人都可以帮助更新这些评论字段吗? 我在陈述中做错了什么?
此外,是否有一个简单的解决方案可以在更新评论后立即更新“TEXT_VALUE”?
谢谢!
你应该替换这一行
db.TEST_Collection.updateMany({ "_id": doc._id },{ "$set": { "1List.Comment": doc.1List.Comment } });})
和
db.TEST_Collection.updateMany({ "_id": doc._id },{ "$set": { "1List.$[].Comment": doc.1List.Comment } });})
您也可以查看文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.