How to update based on existing data in mongo
Sort of a mongo noob, and I have a feeling I am tackling this problem from the wrong direction.
I have about a 7 million document collection. Each document has two fields that I want to modify (not replace), basically they are big strings that have \\n
, and I want to replace those with \n
.
I spent about an hour trying to find a way to "back refe开发者_开发技巧rence" the object returned by the query, which totally doesn't exist. What is the best approach for something like this?
You'll have to query for all the documents and update them one by one. If you do it in JavaScript, it would be something like:
mydb = db.getSisterDB("whateverDBYoureUsing");
var cursor = mydb.foo.find();
while (cursor.hasNext()) {
var x = cursor.next();
/* replace \\n with \n in x's strings ... */
db.foo.update({_id : x._id}, x);
}
You can copy this into a .js file (say, replace.js), change the db and collection names, and run it as a script from the shell:
mongo replace.js
What you want is doing an upsert http://www.mongodb.org/display/DOCS/Updating#Updating-UpsertswithModifiers
精彩评论