Introduction to MongoDB $replaceAll Operator

$replaceAll is a new operator introduced in MongoDB 4.4 that can find and replace all matching substrings within a string. The operator returns a new string with all the matching substrings replaced with the specified replacement string.

Syntax

The syntax for the $replaceAll operator is as follows:

{ $replaceAll: { input: <string>, find: <string>, replacement: <string> } }

Where:

  • input: Specifies the string expression in which the replacement operation is to be performed.
  • find: Specifies the substring expression to be searched and replaced.
  • replacement: Specifies the string expression to be used for replacing each matched substring.

Use Cases

When working with MongoDB’s query language for string operations, the $replaceAll operator is quite useful. It can be used for processing and cleaning data, such as:

  • Removing unwanted characters from a string.
  • Replacing words in text with synonyms.
  • Replacing specific text with other text.

Example

Here is an example of using the $replaceAll operator to replace all spaces in a string with underscores.

Example Data

{ "_id": 1, "name": "John Doe", "address": "123 Main St.", "city": "Anytown, USA"  }
{ "_id": 2, "name": "Jane Doe", "address": "456 Oak Ave.", "city": "Anytown, USA"  }

Example Code

db.collection.aggregate([
  {
    $project: {
      name: { $replaceAll: { input: "$name", find: " ", replacement: "_" } },
      address: {
        $replaceAll: { input: "$address", find: " ", replacement: "_" }
      },
      city: { $replaceAll: { input: "$city", find: " ", replacement: "_" } }
    }
  }
])

Example Result

{ "_id": 1, "name": "John_Doe", "address": "123_Main_St.", "city": "Anytown,_USA" }
{ "_id": 2, "name": "Jane_Doe", "address": "456_Oak_Ave.", "city": "Anytown,_USA" }

Conclusion

The $replaceAll operator is a very useful string manipulation operator that allows for convenient string search and replace. Its syntax is simple and easy to understand, and its use cases are wide-ranging, making it very useful for processing and cleaning data.