MongoDB setOnInsert and push if already existent MongoDB setOnInsert and push if already existent database database

MongoDB setOnInsert and push if already existent


You could implement it without $setOnInsert operator.

db.test.update(  {    name : 'Peter'  },  {    $push : {      "visits.en" : 'today'    }  },  { upsert : true })

If Peter exists, element 'today' will be added to its visits.en array. Else, will be created a document for Peter, with visits object, that will be contain array en with 'today' element.
And I think, that error occured because of you using same property (visits) in two operations ($setOnInsert and $push).


You can still use $setOnInsert but when $setOnInsert and $push doesn't updates in the same fields as mentioned before.

N.b: We use $addToSet if you don't want a duplicated values in your Array

db.test.update(    {      name : 'Peter'    },      {      $setOnInsert: {name : 'Peter'},      $addToSet: {"visits.en": 'today'} // or $push     },     {upsert: true})