Reputation: 3777
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.
Upvotes: 38
Views: 31176
Reputation: 183
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 })
)
Upvotes: 1
Reputation: 3233
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.
Upvotes: 59