Spring Data MongoDB Guide: Relationship Design and Update Strategies
Key point
This guide introduces strategies to resolve the N+1 problem of @DBRef using $lookup and to boost bulk update performance by 24x using bulkOps in Spring Data MongoDB.
Details
The existing @DBRef in Spring Data MongoDB causes the N+1 problem by triggering additional queries during reference resolution. In particular, Kotlin's final classes cannot be lazily loaded due to CGLIB proxy generation failures, making the application of the allOpen plugin essential.
Join Performance and Reference Strategies
Since joins are not possible with find in MongoDB, $lookup from the Aggregation Pipeline must be used. Local benchmark results show that $lookup is overwhelmingly faster at 69.5ms compared to 1167.4ms for @DBRef(lazy=false). Following DDD principles, ID references are recommended between different aggregates, while the Embedded approach is recommended within the same boundary.
Update Safety and Bulk Optimization
The save method replaces the entire document and can cause Lost Updates, so Update().set() should be used to specify only the changed fields. For bulk updates, leveraging bulkOps minimizes I/O round trips. For 10k records, bulkOps achieved approximately 4.5 seconds compared to about 107 seconds for saveAll, demonstrating a 24x performance improvement.
This summary was generated automatically by AI. Check the original for the author's claims and context. Copyright belongs to the original author.
Our guide explains how the AI works. Report summary errors, attribution issues, or removal requests via Contact.