Rogelio Sevilla
Rogelio Sevilla

Reputation: 1

Multiple updates queries in MongoDB

couldn't find information about this, hope it's not a repeated question.

I would like to update multiple documents in MongoDB, but using specific queries and update values for each one, for instance, I have this model:

user: { name: String, email: String }

Lets say that I have 2 documents:

User_A: {
 name: 'Charles Montoya',
 email: '[email protected]'
}
User_B: {
 name: 'Robbin Faz',
 email: '[email protected]'
}

Now, what I would like to do is something like this:

db.user.update([
{ name: 'Robbin Faz' }, { $set: { email: '[email protected]' }, { upsert: true } },
{ name: 'Charles Montoya' }, { $set: { email: '[email protected]' }, { upsert: true} }
])

If something like this is not possible, which way do you recommend me to work with a list of updates?, or should I do a "for"?

Thank you for your help.

Upvotes: 0

Views: 59

Answers (1)

BigDataKid
BigDataKid

Reputation: 1227

You can do a bulk update and or upset:

> var bulk = db.user.initializeUnorderedBulkOp();
> bulk.find( { name: 'Robbin Faz' } ).upsert().update( { $set: { email: '[email protected]' } });
> bulk.find( { name: 'Charles Montoya' } ).upsert().update(  { $set:{ email: '[email protected]' } });
> bulk.execute();

Upvotes: 1

Related Questions