I have documents like this:
{
_id: 'some id',
body: 'i want some apple',
},
{
_id: 'some id2',
body: 'i want some apple and banana',
}
And i want to find and replace all of document's body phrase some apple
to lots of oranges
.
Expected Results:
{
_id: 'some id',
body: 'i want lots of oranges',
},
{
_id: 'some id2',
body: 'i want lots of oranges and banana',
}
So i find all the documents with this:
myDB.find({
"body": {
"$regex": "some apple",
"$options": "i"
}
},
function(err, docs) {
console.log(docs);
}
);
)
But don't know how to replace and update only document's specific body phrase some apple
to lots of oranges
.
How do i do this?
You should consider mongoDB text index
You can implement by creating and index likee this:
db.yourCollectionName.createIndex({ body: "text" });
After which you can run this query:
db.yourCollectionName.updateMany(
{ $text: { $search: "\"some apple\"" }},
{ $set: { body: "i want lots of oranges" }},
{ new: true }
);
That should do it