34

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.

Channa
  • 3,267
  • 7
  • 41
  • 67
  • You can do by create "unique constrain" in Collection. reference : https://groups.google.com/forum/#!topic/mongodb-user/otSQeFN7FJg – IftekharDani Jan 12 '18 at 06:36

2 Answers2

53

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.

Gianfranco P.
  • 10,049
  • 6
  • 51
  • 68
RaR
  • 3,075
  • 3
  • 23
  • 48
0

Edited: I was informed that my solution only works for an array which is not what the original post asked for.

If you are using an array you can use the $addToSet: operator instead of $SetOnInsert.

db.companies.updateOne(
   {"company": "test"},
   { $addToSet: { ["name": "nameValue"]} },
   { new: true })
)
Andreas C
  • 163
  • 1
  • 12
  • 1
    This doesn't do what the asker wanted. If the field exists, and is an array, it will be updated, if the field exists and is not an array, It will return an error, and if the field does not exists it will be added. – Joe Apr 08 '21 at 15:46