Mongoose 查找并替换文档中的特定短语

Mongoose find and replace specific phrase the document

我有这样的文件:

    {
      _id: 'some id',
      body: 'i want some apple',
    },

    {
      _id: 'some id2',
      body: 'i want some apple and banana',
    }

我想找到所有文档的正文短语 some apple 并将其替换为 lots of oranges

预期结果:

    {
      _id: 'some id',
      body: 'i want lots of oranges',
    },

    {
      _id: 'some id2',
      body: 'i want lots of oranges and banana',
    }

所以我找到了所有的文档:

    myDB.find({
        "body": {
          "$regex": "some apple",
          "$options": "i"
        }
      },
      function(err, docs) {
        console.log(docs);
      }
    );
)

但不知道如何仅将文档的特定正文短语 some apple 替换和更新为 lots of oranges

我该怎么做?

你可以循环更新

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

你应该考虑mongoDB text index

您可以像这样创建和索引来实现:

db.yourCollectionName.createIndex({ body: "text" });

之后您可以 运行 这个查询:

db.yourCollectionName.updateMany(
      { $text: { $search: "\"some apple\"" }},
      { $set: { body: "i want lots of oranges" }},
      { new: true }
);

应该这样做