0

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?

bmer
  • 47
  • 9
  • If you are using `mongodb 4.2` version which allows `aggregation pipeline` in update. [This does it](https://stackoverflow.com/a/56556298/6082280) – ambianBeing Sep 26 '19 at 16:36
  • Possible duplicate of [How to replace substring in mongodb document](https://stackoverflow.com/questions/12589792/how-to-replace-substring-in-mongodb-document) – ambianBeing Sep 26 '19 at 16:37

2 Answers2

4

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

Ashok
  • 2,846
  • 1
  • 12
  • 20
O'Dane Brissett
  • 1,284
  • 1
  • 8
  • 23
2

you can loop through and update

db.people.find({
    body: {
        $regex: "some apple",
        $options: "i"
    }
}).forEach(doc => {
    doc.body = doc.body.replace(/some apple/ig, 'lots of oranges');
    db.people.update({ _id: doc._id }, { $set: { body: doc.body } });
});  
Ja9ad335h
  • 4,995
  • 2
  • 21
  • 29