0 votes
in MongoDB by
How to update based on existing data in mongo

1 Answer

0 votes
by
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 , and I want to replace those with n.

I spent about an hour trying to find a way to “backreference” the object returned by the query, which totally doesn’t exist. What is the best approach for something like this in MongoDB?

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 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

Related questions

0 votes
asked Jun 17, 2020 in MongoDB by AdilsonLima
+1 vote
asked Jun 3, 2020 in MongoDB by Robindeniel
...