Mongodb how to insert ONLY if does not exists (no

2020-07-02 11:53发布

问题:

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.

回答1:

You can use $setOnInsert like,

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

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



标签: mongodb