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.
ASP.NET Core 3 MVC Application with MongoDB You can use upsert i.e. whenever you insert a value and it already exist then update would be performed. If the value does not already exist then it would get inserted.
If a collection does not exist, MongoDB creates the collection when you first store data for that collection. You can also explicitly create a collection with various options, such as setting the maximum size or the documentation validation rules.
In MongoDB, we can check the existence of the field in the specified collection using the $exists operator. When the value of $exists operator is set to true, then this operator matches the document that contains the specified field(including the documents where the value of that field is null).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With