Last updated: 2024-03-19

  1. Learn
  2. Spring Data MongoDB
  3. Adding Relations

Using @DocumentReference for relations in Spring Boot MongoDB

To establish relations between documents, MongoDB recommends the use of manual references. Using @DocumentReference we can follow this recommendation in our Spring Boot application and at the same time resolve the linked document without any additional code.

Before version 3.3.0 of Spring Data MongoDB, a manual reference could only be established by storing the plain ID of a linked document. Determining the target document then had to be done additionally in the code by starting an explicit query.

Resolving a manual reference before

Nowadays the new annotation @DocumentReference is available. This falls back on the fast manual reference and only stores the ID of the linked document in MongoDB. At the same time, we can transparently access the target document in the code without having to worry about the additional query.

Linking another Document transparently with a manual reference

@DocumentReference can be specified on both sides of a relation. For this one side must be extended with @ReadOnlyProperty as well as a lookup query to resolve the reference via the source document. All common types like One-to-One, Many-to-one and Many-to-many are supported. With Many-to-many a list of IDs of the target document is stored in the database - no intermediate table / collection is created.

Parent side of our One-to-one relation

Setting lazy = true can be recommended for the vast majority of cases. Unlike JPA, where the initial data is loaded with a join, a new query against MongoDB is always necessary to resolve the relation. Doing this only when the linked document is actually accessed can potentially save the additional query.

Bootify can be used to define a Spring Boot application for MongoDB with custom documents and relations. For this purpose @DocumentReference is generated automatically including the lookup query, and the runnable application is available for download.

Learn more
or see pricing

Further readings

Manual references vs DBRefs