1

I want to replace a substring "are" with "any test" in all "ques" document of "user" collection,but my query is replace the full document string with "any test".I am new to mongo. Please someone suggest me what wrong with my query?

Here is my mongo query.

db.user.find({ques:{$regex:'are'}}).forEach(function (e, i) {e.ques =  e.ques.replace(/are/, 'any test'), printjson(e); db.ques.save(e);} )
  • Does this answer your question? [How to replace substring in mongodb document](https://stackoverflow.com/questions/12589792/how-to-replace-substring-in-mongodb-document) – PZBird Jan 18 '23 at 06:43
  • PZBird.this command db.faq.find().forEach(function(o) {o.ques = o.ques.replace(/hello/, "How"); printjson(o);db.faq.save(o)}) is okay in localhost but in server it show that "db.faq.save" is not a function – Ratnambar Gupta Jan 18 '23 at 07:29

1 Answers1

1

Try with:

db.user.find({ ques: { $regex: 'are' } }).toArray((err, users) => {
    if (err) return;
    for (const u of users) {
        u.ques = u.ques.replace(/are/, 'any test');
        db.user.save(u);
    }
});
lpizzinidev
  • 12,741
  • 2
  • 10
  • 29