How to Replace Characters in MongoDB


TL; DR: As of MongoDB 6.0, this is how I learned to replace some characters in a field in all documents. In the example below all “.” characters in field_name will be replaced by “_” character:

db.collection.updateMany(
  {field_name: /\./}, 
  [
  	{ $set: 
      { field_name: 
        { $replaceAll: 
          { input: "$field_name", find: ".", replacement: "_"}
        }
      }
    }
  ]
)

The backstory is when using MongoDB with MongoEngine, there’s an issue when a key in a dictionary field contains the ‘.’ character: Problem handling dots in DictField keys so I needed to replace all dots in existing documents.

🙂