Replace Substring in MongoDB document

Replace Substring in MongoDB document shell Replace Substring in MongoDB document

Today this article will learn to write a query to replace substring in MongoDB document with an example.

We will replace a string in the Mongo document with the input string using a simple and easy approach i.e using $replaceOne aggregation operator.

We will cover below aspects,

 

We will update the records using the Mongo shell query.

We already looked at a simple way of adding or updating a new field to the document in our previous MongoDB sample series.

Getting started

Here below is a sample schema or document we shall use,


Replace Substring in MongoDB using replaceOne Aggregator

We are going to use a newly introduced aggregate operator to replace easily a string with matching criteria with part of the string.

What is $replaceOne

$replaceOne is aggregation operator which helps replace the first instance of a search string in an input string with a replacement string.

This operator usage is case-sensitive.

Query Pattern Replace using $replaceOne

{ 
$replaceOne: { 
    input: <expression>, 
    find: <expression>, 
    replacement: <expression>}
}

In the above query,

inputInput string with search criteria.
findFind the document with matching input string criteria.
replacementThe string to use to replace the first matched instance from input

You can replace the existing Mongo field using any other fields from the document using the above approach + using the approach discussed here.

Example using $replaceOne

In the below example, we will replace “total-order” with “order” in the mongo field.

Example

db.Orders.updateMany(
{ 
  Link: { 
    $regex: /total-order/ 
  } 
}, 
[{ 
  $set: { 
    Link: { 
      $replaceOne: { 
        input: "$Link", 
        find: "total-order", 
        replacement: "order" 
      } 
    } 
  } 
}])

Below is the schema post-update,

Replace Substring in MongoDB document

That’s all! Happy coding!

Does this help you fix your issue?

Do you have any better solutions or suggestions? Please sound off your comments below.



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

Your email address will not be published. Required fields are marked *