0

How would I update every record in the "title" collection for mongo, to make a field named LastReturnedName set to Name for every single record?

Thought it would be something like this:

db.title.update( 
    { "LastNameReturned" : "" }, 
    { $set:{ "LastNameReturned" : Name } }, 
    { multi : true } 
);
chridam
  • 100,957
  • 23
  • 236
  • 235

1 Answers1

1

You can use foreach iteration:

db.title.find({ "LastNameReturned" : "" }).snapshot()
  .forEach(function(t) {
      db.title.update({_id: t._id}, {$set: {"LastNameReturned" : t.Name}});
   });

NOTE: You can use snapshot() only with unsharded collections. Also you can speed up updating if you'll use bulk operation.

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
  • Hi - thank you for the response. it says script executed successfully. but there are no results to show. It appears LastReturnedName is still null on titles. Is this supposed to work for all records in the collection, or is the t._id supposed to match to some id we pass in? ... Also what's unsharded? – Mitchell McLaughlin Feb 02 '17 at 13:16
  • @MitchellMcLaughlin t._id supposed to match _id of document which you are updating in forEach function. Make sure Name field exists and has non-null value – Sergey Berezovskiy Feb 02 '17 at 13:21
  • Ok - thanks. Do you have anything else to try maybe? This one didn't seem to update any of the titles! – Mitchell McLaughlin Feb 02 '17 at 13:26
  • @MitchellMcLaughlin there is no need in something else - this query should update each matching document. Seems like you don't have matching documents. Maybe your `LastNameReturned` field is not empty string. Maybe it has null value? – Sergey Berezovskiy Feb 02 '17 at 13:33
  • 1
    Oh, i'm sorry!! this is correct. it did work! :) But maybe it only grabs X number of records.. looks like about 100. Is there a way to literally update ALL of them? i have about 100k ! :) – Mitchell McLaughlin Feb 02 '17 at 13:40
  • @MitchellMcLaughlin that should update all of them, but one-by-one update might take pretty big time. Probably there is limitation of mongo management tool which you are using. You can use https://docs.mongodb.com/manual/reference/method/Bulk.find.update/ to update documents in batches (e.g. by 1000). Sample for insert http://stackoverflow.com/questions/33911208/mongodb-foreach-for-nested-collection-to-update-copy-documents-to-another-collec – Sergey Berezovskiy Feb 02 '17 at 13:48