0

I have a collection that has a number of documents where the title contains encoded & characters (&) and I would like to convert these back.

I'm wondering if it is possible to do a string replacement on a value based on it's original value.

For example with the document below:

{
   title: "this & that"
}

Is it possible to replace the & with a normal update statement? I tried something like this:

db.questions.update({title: /&/}, {title: title.replace(/&/g, "&")});

But it threw the following error: ReferenceError: title is not defined

Can it be done using an update statment? If not, is the best way just to do a find/foreach/update on each document?

1 Answer 1

1

I'm wondering if it is possible to do a string replacement on a value based on it's original value....Can it be done using an update statment?

Currently, it is not possible to update a field's value in mongodb by accessing,modifying its original value in a single update statement.

But it threw the following error: ReferenceError: title is not defined

This error occurs, because Mongodb does not see the title field of the document that is getting updated in its scope.

If not, is the best way just to do a find/foreach/update on each document?

Yes. You need to do it that way.

db.collection.find({"title":/&amp/}).forEach(function(doc){
db.collection.update({"_id":doc._id},
                     {$set:{"title": doc.title.replace(/&/g, "&")}})
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.