MongoDB 4.4 introduced nine new aggregation pipeline operators, including two new operators for finding and replacing a substring.
The two new operators that allow you to find and replace a substring are the $replaceOne and $replaceAll operators.
Here’s what each operator does:
| Operator | Description |
|---|---|
$replaceOne | Replaces the first instance of a search string in an input string with a replacement string. |
$replaceAll | Replaces all instances of a search string in an input string with a replacement string. |
The only difference between these operators is that $replaceOne replaces the first instance of the substring, whereas $replaceAll replaces all instances of the substring.
The $replaceOne Operator
Suppose we have a collection called products with the following document:
{
"_id" : 1,
"product" : "Left Handed Screwdriver with Left Handed Carry Case"
}
We can use the $replaceOne operator to replace the first instance of the substring Left Handed with another string:
db.products.aggregate([
{
$project:
{
product: { $replaceOne: { input: "$product", find: "Left Handed", replacement: "Ambidextrous" } }
}
}
]).pretty()
Result:
{
"_id" : 1,
"product" : "Ambidextrous Screwdriver with Left Handed Carry Case"
}
Notice that there are actually two instances of the substring (Left Handed) but only the first instance was replaced.
The $replaceAll Operator
In the previous example, we replaced the first instance of the substring.
Now let’s use the $replaceAll operator to replace all instances of the substring:
db.products.aggregate([
{
$project:
{
product: { $replaceAll: { input: "$product", find: "Left Handed", replacement: "Ambidextrous" } }
}
}
]).pretty()
Result:
{
"_id" : 1,
"product" : "Ambidextrous Screwdriver with Ambidextrous Carry Case"
}
This time both instances of the substring (Left Handed) were replaced.