0

I am pretty sure how INSERT works in mongodb, but I want insert to insert the data and in case the Id already exists I want to update the data like SAVE in mongodb.

Example:

If my entry in test collection is like,

{ "_id":ObjectId("68768242ge"), "name":"1"  } 

I know using save am able to update the current data as

db.test.save({ "_id":ObjectId("68768242ge"), "name":"2"  }) 

But the list update is possible only using INSERT query.

db.test.insert({ "_id":ObjectId("68768242ge"), "name":"2"  }) 

I will get an error in this case as a duplicate key.

So I want to do both the operation, If the object is not there, Then I want to insert it but where as if the Object key already exists then I want to update it.

Is there any way through which we can achieve it? I want to do the bulk insert / update using mongodb.

halfer
  • 19,824
  • 17
  • 99
  • 186
Harry
  • 3,072
  • 6
  • 43
  • 100
  • 1
    There's no bulk save operation that behaves that way you want. – WiredPrairie Dec 04 '13 at 11:38
  • Thanks wiredprairie for ur reply. then what is the best way to achieve that in mongodb – Harry Dec 06 '13 at 00:00
  • Changes are being made to support bulk operations in 2.6, but this is not yet available: http://docs.mongodb.org/master/release-notes/2.6/#new-write-commands – Trisha Dec 31 '13 at 09:20

1 Answers1

1

What you want to do is called "upsert".

Some updates also create records. If an update operation specifies the upsert flag and there are no documents that match the query portion of the update operation, then MongoDB will convert the update into an insert.

> db.test.update({"_id" : ObjectId("529f4ddd6487ccbe70e44c75")},{"name":"orig"},{upsert: true})
> db.test.find(); { "_id" : ObjectId("529f502aef047d0c12c305d5"), "name" : "orig" }
> db.test.update({"_id" : ObjectId("529f502aef047d0c12c305d5")},{"name":"new"},{upsert: true});
> db.test.find(); { "_id" : ObjectId("529f502aef047d0c12c305d5"), "name" : "new" }

You can check the MongoDB documentation of db.collection.update().

Lachezar Balev
  • 11,498
  • 9
  • 49
  • 72
  • Thanks lucho for ur reply, I know about upsert, I checked the performance of all the three, INSERT, UPDATE and SAVE. In INSERT, I tried with bulk insert option, But In update I tried with UPSERT with looping the list and SAVE with looping. It clearly shows that performance of INSERT in bulk operation is tremendous compared to update but where as the SAVE is worst. so what I need is " I want insert to insert the data and In case the Id already exists then it has to be updated " – Harry Dec 05 '13 at 23:50
  • Guys Is there any way to insert with update if there is any key already exists in the bulk insert. – Harry Dec 05 '13 at 23:58