Bulk operations reduce request overhead but do not carry every per-entity callback and version behavior of repository saves.
Spring Data MongoDB bulk writes: fewer round trips, different lifecycle behavior
A batch is not N ordinary saves
A nightly allocation import writes thousands of independent documents. MongoTemplate bulk operations group writes into fewer requests, which can lower network overhead. That does not make a bulk update equivalent to calling save on each aggregate. Lifecycle event publication is limited for bulk work, and version behavior depends on the chosen operation. A service that relies on callbacks for audit or validation may silently lose that work when switched to bulk.
Choose failure ordering
Ordered bulk execution stops at a failed operation; unordered execution can continue with other writes. Neither mode automatically gives a business-level all-or-nothing import. Record a source digest and per-row outcome, reject duplicate import IDs, and reconcile partial success. Batch input identity and quarantine are useful when the import spans many chunks.
Measure the actual gain
Compare request count and elapsed time on realistic document sizes. Inject one duplicate-key failure in the middle and inspect which records committed. Verify any versioned document behavior explicitly against the optimistic-locking contract. The snippet only names the operation mode; import validation and result reconciliation remain application code.
Implementation sketch
BulkOperations writes = mongoTemplate.bulkOps(
BulkOperations.BulkMode.ORDERED, ParcelAllocation.class);
writes.insert(validatedAllocations);
BulkWriteResult result = writes.execute();
assertEquals(validatedAllocations.size(), result.getInsertedCount());Cost and verification
Bulk writes save round trips but can increase the size of a failed unit. Memory and server work scale with batch size; keep a bounded chunk and record partial outcomes.
Common Mistakes
- Do not assume bulk operations trigger every repository lifecycle callback.
- Do not call an ordered bulk import an atomic transaction.
- Do not ignore partial success when one row is rejected.
Read next
Spring Data MongoDB optimistic locking: save the version you read, Spring Data MongoDB tenant uniqueness: enforce it in an index, Spring Batch restart input: pin the manifest before resuming a cursor, Spring Batch SkipListener: persist a rejection key with the skipped row.
