Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data MongoDB support bulk insert/save

I have been google for a while, not sure whether Spring Data MongoDB supports for bulk save.

I need to save a collection of documents into mongo as atomic, either all saved or none saved.

Can anyone share a link or some sample code for this?

like image 967
jasonfungsing Avatar asked Oct 02 '12 06:10

jasonfungsing


People also ask

What is batch insert in MongoDB?

Multiple documents can be inserted at a time in MongoDB using bulk insert operation where an array of documents is passed to the insert method as parameter.

Can we use Spring data JPA with MongoDB?

Yes, DataNucleus JPA allows it, as well as to many other databases.

Which is better MongoTemplate or MongoRepository?

So I'd say that MongoTemplate is a better option, unless you have a very elaborated POJO model or need the custom queries capabilities of MongoRepository for some reason. Good points/examples. However your race condition example and undesired result can be avoided using @Version to prevent that very scenario.

What is the difference between MongoOperations and MongoTemplate?

MongoTemplate provides a simple way for you to save, update, and delete your domain objects and map those objects to documents stored in MongoDB. You can save, update and delete the object as shown below. MongoOperations is the interface that MongoTemplate implements.


1 Answers

When you do a save through MongoDB Java driver you can only pass a single document to MongoDB.

When you do an insert, you can pass a single element or you can pass an array of elements. The latter is what will result in a "bulk insert" (i.e. single insert command by client will result in multiple documents being inserted on the server).

However, since MongoDB does not support a notion of transaction, if one of the inserts fails there is no way to indicate that previously inserted documents should be deleted or rolled back.

For the purposes of atomicity, each document insert is a separate operation and there is no supported way to make MongoDB either insert all or none.

If this is something that your application requires there may be other ways to achieve it: - change your schema so that these are subdocuments of a single parent document (then there is technically only one "insert" of the parent document) - write the transaction semantics into your application code - use a database which natively supports two phase commit transactions.

like image 55
Asya Kamsky Avatar answered Sep 22 '22 16:09

Asya Kamsky