Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top