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
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
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:
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.
How about this? without regex
Mongodb playground