flimflam57
flimflam57

Reputation: 1334

Change name in collection with multiple documents in MongoDB and Meteor

If I have a collection with multiple documents for one person like:

{ FullName: "Jane Doe", Camp: "may12", Week1: "0", Week2: "1", Week3: "0" }
{ FullName: "Jane Doe", Camp: "may13", Week1: "0", Week2: "0", Week3: "1" }
{ FullName: "Jane Doe", Camp: "may14", Week1: "0", Week2: "1", Week3: "0" }

and I need to update her name to "Jane Smith", I get her name from a Session:

var nameAddressFullName = Session.get('clientName');

Get all the documents with her name in put them into an array:

var documentNameAddressP = Programs.find({ FullName: nameAddressFullName}).fetch();

Then try to update all the names (I need to update based on _id values only), I'd need something like:

Programs.update({ _id: {$in: {documentNameAddressP._id}}, {$set: {FullName: nameChange}}); //????

We need to update all Jane Doe's documents to the full name Jane Smith keeping all the rest of the properties intact.

Upvotes: 0

Views: 96

Answers (2)

Michel Floyd
Michel Floyd

Reputation: 20226

If you do this update via a method call to server then you can bulk update all the documents there in one go with {multi: true} in your update query.

From the client you can easily iterate over the cursor:

Programs.find({ FullName: nameAddressFullName}).forEach(function(doc){
  Programs.update({ _id: doc._id },{ $set: { FullName: nameChange }});
});

Upvotes: 1

Mazout
Mazout

Reputation: 104

You can select element to update in update query:

Programs.update({FullName: nameAddressFullName},{$set: {FullName: nameChange}}) 

https://docs.mongodb.org/manual/reference/operator/update/set/

Upvotes: 0

Related Questions