jacky
jacky

Reputation: 524

mongo add or update an object in an array

I have a document:

{ _id: ObjectId("5af06ec792e0fd001f86661d"), 
 'company': 'ABC', 
 'profile_set' :
   [
     { 'name' : 'nick', 'options' : 0 },
     { 'name' : 'joe',  'options' : 2 },
     { 'name' : 'burt', 'options' : 1 }
   ] 
}

and would like to add a new document to the profile_set set if the name doesn't already exist OR if it exists then update the existing one.

So in this example if I tried to add:

{'name' : 'matt', 'options' : 0}

it should add it, but adding

{'name' : 'nick', 'options' : 8}

should do update the one with name nick because that object already exists with name nick and it will update it other fields value to the new one.

db.coll.update(
    {_id: id, 'profile_set.name': {$ne: 'nick'}}, 
    {$push: {profile_set: {'name': 'nick', 'options': 8}}})

this above command will only add it if it doesn't exist. How can i modify it so that if it exists, the update it with the new values?

update:

I want to find and update as above any document that has 'company': 'ABC'.

Upvotes: 2

Views: 747

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151170

What you want is bulkWrite() where you issue both operations to $push where not there and $set the "matched" array element in the same server request:

db.coll.bulkWrite([
  { "updateMany": {
    "filter": { company: "ABC", "profile_set.name": "nick" },
    "update": {
      "$set": { "profile_set.$.options": 8 }
    }
  }},
  { "updateMany": {
    "filter": { "company": "ABC", "profile_set.name": { "$ne": "nick"} },
    "update": {
       "$push": { 
         "profile_set": { "name": "nick", "options": 8 }
       }
    }
  }}
])

And under bulkWrite() the variant operation is "updateMany" which is effectively the same as the "multi": true option or the updateMany() method, except we are issuing in "batch".

Upvotes: 4

Related Questions