Home > Enterprise >  Update one or two fields in an array for all documents in a collection - mongo db
Update one or two fields in an array for all documents in a collection - mongo db

Time:11-22

First of all, I am using Mongo DB Compass and the mongo shell. I want to update for example this field: 1List.Comment

In this Field I want to replace 'ß' with 'ss'

1List is an array. And in this Array I can have several Objects. These Objects contain the 'Comment' field.

Here is one example Doc:

{
   "_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"
      }
   ]
}

This is what I have tried in 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 } });})

But I get the error message: Cannot create field 'Comment' in element {1List:.......

Can anybody help to get these Comment fields updated? What am I doing wrong in my statement?

And also, is there an easy solution to also update 'TEXT_VALUE' right after updating Comment?

Thank you!

CodePudding user response:

You should replace this line

db.TEST_Collection.updateMany({ "_id": doc._id },{ "$set": { "1List.Comment": doc.1List.Comment } });})

with

db.TEST_Collection.updateMany({ "_id": doc._id },{ "$set": { "1List.$[].Comment": doc.1List.Comment } });})

You can check the docs too.

  • Related