Reputation: 85126
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?
Upvotes: 0
Views: 92
Reputation: 19700
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":/&/}).forEach(function(doc){
db.collection.update({"_id":doc._id},
{$set:{"title": doc.title.replace(/&/g, "&")}})
})
Upvotes: 1