bmer
bmer

Reputation: 47

Mongoose find and replace specific phrase the document

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?

Upvotes: 0

Views: 1080

Answers (2)

O'Dane Brissett
O'Dane Brissett

Reputation: 1283

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

Upvotes: 4

Ja9ad335h
Ja9ad335h

Reputation: 5075

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 } });
});  

Upvotes: 2

Related Questions