MongoDB Node.js to Replace String in Document

Replace Substring in MongoDB document shell MongoDB Nodejs to Replace String in Document

Today this article will see how to write a query using MongoDB Node.js to replace string or substring In a Document

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 which is supported in MongoDB v4.0 onwards.

We will cover below aspects,

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 -MongoDB Node.js to Replace String

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


Node.js – 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.

Node.js Example using $replaceOne

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

Please add below using namespace

import { MongoClient } from 'mongodb';

Define the Regex query for the matching string,

'Link': {     
     '$regex': new RegExp('total-order')   
 }

Define the Set using replaceOne Operator,

'$set': {
      'Link': {
        '$replaceOne': {
          'input': '$Link', 
          'find': 'total-order', 
          'replacement': 'order'
        }
      }
    }

Example


const filter = {
  'Link': {
    '$regex': new RegExp('total-order')
  }
},[
  {
    '$set': {
      'Link': {
        '$replaceOne': {
          'input': '$Link', 
          'find': 'total-order', 
          'replacement': 'order'
        }
      }
    }
  }
];
const client = await MongoClient.connect(
  'mongodb://host/',
  { useNewUrlParser: true, useUnifiedTopology: true }
);

const coll = client.db('TheCodeBuzz').collection('Orders');
const cursor = coll.find(filter);
const result = await cursor.toArray();
await client.close();

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 *