Combining bulk Insert and Save in mongodb using Java? Is there a way through which we can achieve it?

579 views Asked by At

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.

1

There are 1 answers

2
Lachezar Balev On

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