mongodb

Mongodb how to insert ONLY if does not exists (no update if exist)?


How can I insert a document if it does not exist while not updating existing document if it exists?

let's say I have a document as follows:

  {
          "company":"test", 
          "name":"nameVal"
}

I want to check whether the collection contains company test, if it doesn't exist I want to create a new document. If it exists I want to do NOTHING. I tried update with upsert = true. But it updates the existing document if it exists.

This is what I tried:

db.getCollection('companies').update(
    {
  "company": "test"
  },
  {
  "company": "test",
  "name": "nameVal2"
},
{upsert:true}
)

Appreciate any help to resolve this using one query.


Solution

  • You can use $setOnInsert like,

    db.companies.updateOne(
       {"company": "test"},
       { $setOnInsert: { "name": "nameVal2", ... } },
       { upsert: true }
    )
    

    If this update operation does not do insert, $setOnInsert won't have any effect. So, the name will be updated only on insert.