Search code examples
mongodbspring-bootperformance

MongoDB - Spring Boot performance issue for document system design


Let's assume we have 2 or more MongoDB documents that are related to each other. When managing them, I'm confused about two approaches. The first approach is to put each other's IDs inside the MongoDB documents on the Java side.

For Example:

@Document
public class Customer {

   @MongoId
   private String id;
   private String addressId;
}

Second Approach: Using DocumentReference

@Document
public class Address {
    @MongoId
    private String id;
    
    @DocumentReference(lazy = true, lookup = "{ 'primaryAddress' : ?#{#self._id} }")
    @ReadOnlyProperty
    private Customer customer;
}

@Document
public class Customer {

    @MongoId
    private String id;
    @DocumentReference(lazy = true)
    private Address primaryAddress;

}

Which of these two approaches is more performance-efficient? Which one allows me to get the job done with fewer queries? Could you evaluate these in general terms?


Solution

  • When developing with MongoDB and Spring Boot, there are different approaches you can take with regards to storing references between documents:

    1. Storing IDs as Strings:

      • Advantages:
        • Faster read operations since there's no need for an additional query.
        • Simplifies querying on the application side.
      • Disadvantages:
        • If there's a change in the referenced document, you might have to update it across all related documents.
        • Might result in data redundancy in the database.
    2. Using DocumentReference:

      • Advantages:
        • Provides a normalized structure; changes to a document reflect across all referenced documents.
        • Potentially less data redundancy.
      • Disadvantages:
        • Reading operations might be slower since it might require an additional query.
        • Might require writing more complex queries.

    Which method is more effective depends on your application's requirements and usage scenarios:

    • If your application involves frequent read operations and performance is a critical factor, storing IDs as strings might be more beneficial.
    • If data integrity, update operations, and avoiding redundant data are important, then using DocumentReference might be more suitable.

    The choice of which approach to adopt will depend on your project's specific requirements and priorities.