0

How can you perform a dynamic document update in MongoDB? (from the terminal application mongo, not by having to use additional libraries like mongoose for nodejs)

My first attempt didn't seem to actually update anything:

db.people.find().forEach( function(myDoc) { myDoc.field = myDoc.field.replace(/\/./g, '/'); } );

The update documentation at http://docs.mongodb.org/manual/reference/method/db.collection.update/#update-parameter only seems to discuss "static" updates (so you can't use the exist value of a document's attribute to determine what the new value should be).

Do I need to use the MapReduce feature some how?

Trindaz
  • 17,029
  • 21
  • 82
  • 111
  • You cannot update the value of a field based on the value of "another" field at present. But surely what you are doing is simply a `regex` match on the selection side with a "fixed" value to update on the "update" side. So why cannot you simply do just that? – Neil Lunn May 19 '14 at 11:46
  • @NeilLunn the value is unique, so if I understand you correctly that would mean I'd be forced to run n queries for n documents which doesn't sound fun. – Trindaz May 19 '14 at 12:52

1 Answers1

1

You've got the right approach to do this one doc at a time, but you need to call save on the collection to commit your change to myDoc:

db.people.find().forEach( function(myDoc) { 
    myDoc.field = myDoc.field.replace(/\/./g, '/'); 
    db.people.save(myDoc);
} );
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • Additional observation after using this solution: the order of fields in output from `db.people.find()` which was consistent is now changed to almost the same as before, but with _id appearing first in the list. IDK what this means, if anything, but it makes me wonder what else changed about the document state after using `db.people.save()` – Trindaz May 19 '14 at 12:56
  • @Trindaz That's normal: http://stackoverflow.com/questions/5046835/mongodb-field-order-and-document-position-change-after-update – JohnnyHK May 19 '14 at 13:04