猫鼬查找并替换文档的特定短语



>我有这样的文档:

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

我想找到并替换文档的所有正文短语some applelots 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 applelots of oranges

我该怎么做?

你应该考虑mongoDB文本索引

您可以通过创建和索引来实现,如下所示:

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

之后,您可以运行此查询:

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

那应该可以做到

你可以循环和更新

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

最新更新