Welcome to plsql4all.blogspot.com SQL, MYSQL, ORACLE, TERADATA, MONGODB, MARIADB, GREENPLUM, DB2, POSTGRESQL.

Friday, 23 February 2024

Replace Function in MongoDB

In MongoDB, you can use the $replaceOne aggregation operator to replace occurrences of a specified string with another string within a field. This operator is used within aggregation pipelines to update documents in a collection.


Here's the syntax of the $replaceOne operator in MongoDB:

{

  $replaceOne: {

    input: <input>,

    find: <substring_to_replace>,

    replacement: <replacement_string>

  }

}


- input: The field that contains the string you want to update.

- find: The substring you want to replace.

- replacement: The string to replace occurrences of find.


Example:

Suppose you have a collection named data with documents like this:


{ "_id": 1, "text": "hello world" }


You can use the $replaceOne operator to replace occurrences of 'world' with 'universe':

db.data.aggregate([

  {

    $replaceOne: {

      input: "$text",

      find: "world",

      replacement: "universe"

    }

  }

])

This will return a document with the updated text field:


{ "_id": 1, "text": "hello universe" }

This example demonstrates how to replace occurrences of a substring within a string field using the $replaceOne operator in MongoDB's aggregation framework.

No comments:

Post a Comment

Please provide your feedback in the comments section above. Please don't forget to follow.