为集合中的所有文档更新数组中的一个或两个字段 - mongo db

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是一个数组。在这个数组中我可以有几个对象。 这些对象包含 'Comment' 字段。

这里是一个示例文档:

{
   "_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: 'List',
        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:.......

中创建字段 'Comment'

有人可以帮助更新这些评论字段吗? 我的陈述哪里做错了?

另外,是否有一个简单的解决方案可以在更新评论后立即更新 '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 } });})

您也可以查看 docs