skip to Main Content

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"
}]

3

Answers


  1. Chosen as BEST ANSWER

    1st i'm storing all numbers with respective _id to the variable a, then iterate the collection with forEach function and updating the document. This code help me out in this problem statement

    var a = db.coll.find({},{"NUMBER":1})
    
    a.forEach(function( row ) {
    var dict = '*****'+row.NUMBER.substring(5,row.NUMBER.length);
    db.coll.updateOne({"_id" : row._id},{$set : {"NUMBER" : dict}});
    });
    

  2. 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.

    Login or Signup to reply.
  3. How about this? without regex

    Mongodb playground

    db.collection.aggregate([
      {
        $set: {
          NUMBER: {
            $concat: [
              "*****",
              {
                $substrCP: [
                  "$NUMBER",
                  5,
                  {
                    $strLenCP: "$NUMBER"
                  }
                ]
              },
              
            ]
          }
        }
      }
    ])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search