Home > Software design >  how to replace first 5 occurrences in string using mongodb query
how to replace first 5 occurrences in string using mongodb query

Time:01-25

How to replace the first n occurance of string in mongodb database. sample JSON :

[{
"NAME":"Peter Parker",
"NUMBER":"6882859392"
},
{
"NAME":"Jhon Ripper",
"NUMBER":"9285346361"
},
{
"NAME":"James",
"NUMBER":"8754859390"
}]

i want to update 1st 5 occurence of NUMBER field of whole JSON

Expected output:

[{
"NAME":"Peter Parker",
"NUMBER":"*****59392"
},
{
"NAME":"Jhon Ripper",
"NUMBER":"*****46361"
},
{
"NAME":"James",
"NUMBER":"*****59390"
}]

CodePudding user response:

In MongoDB, you can use the updateMany() method to update multiple documents that match a specific condition. In your case, you want to update the first 5 occurrences of the "NUMBER" field.

Here is an example of how you can use the updateMany() method to update the first 5 occurrences of the "NUMBER" field in your JSON:

// Define a filter to find the first 5 occurrences of the "NUMBER" field
var filter = { NUMBER: { $regex: /^[0-9]{5}/ } };

// Define the update operation
var update = { $set: { NUMBER: "*****"   "$"   "NUMBER" } };

// Use the updateMany() method to update the documents that match the filter
db.yourCollectionName.updateMany(filter, update);

The filter { NUMBER: { $regex: /^[0-9]{5}/ } } uses a regular expression to find the documents where the value of the "NUMBER" field starts with 5 digits.

The update { $set: { NUMBER: "*****" "$" "NUMBER" } } uses the $set operator to update the "NUMBER" field to a string that starts with "*****" and concatenates the rest of the original number using the $ operator.

The updateMany() method updates all the documents that match the filter, in your case the first 5 occurrences of NUMBER field.

Please keep in mind that you need to be connected to a MongoDB server and a specific database before running this code.

CodePudding user response:

How about this? without regex

Mongodb playground

db.collection.aggregate([
  {
    $set: {
      NUMBER: {
        $concat: [
          "*****",
          {
            $substrCP: [
              "$NUMBER",
              5,
              {
                $strLenCP: "$NUMBER"
              }
            ]
          },
          
        ]
      }
    }
  }
])
  • Related