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);} )
2
  • Does this answer your question? How to replace substring in mongodb document Commented Jan 18, 2023 at 6: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 Commented Jan 18, 2023 at 7:29

1 Answer 1

0

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);
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

Hii @lpizzinidev I found "MongoServerError: Expected field projectionto be of type object" error
@RatnambarGupta Try with toArray (see edited answer)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.