Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 775
Channa Avatar asked Jan 12 '18 06:01

Channa


People also ask

Does MongoDB update insert if not exists?

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.

Does MongoDB Create collection if not exists?

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.

How do you check if a field does not exist MongoDB?

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).


1 Answers

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.

like image 192
RaR Avatar answered Sep 21 '22 09:09

RaR