A Guide to @DBRef in MongoDB – MongoDB中的@DBRef指南

最后修改: 2022年 3月 18日

1. Overview


In this tutorial, we’ll look at Spring Data MongoDB’s @DBRef annotation. We’ll connect MongoDB documents using this annotation. Additionally, we’ll see the types of MongoDB database references and compare them as well.

在本教程中,我们将了解 Spring Data MongoDB 的 @DBRef 注解。我们将使用该注解连接MongoDB文档。此外,我们还将看到MongoDB数据库引用的类型,并对它们进行比较。

2. MongoDB Manual Database Reference


The first type that we discuss is called the manual reference. In MongoDB, every document must have an id field. Therefore, we can rely on using it and connect documents with it.


When using manual references, we store the _id of the referenced document in another document. 


Later on, when we are querying data from the first collection, we can start a second query to fetch the referenced documents.


3. Spring Data MongoDB @DBRef Annotation

3.Spring Data MongoDB @DBRef 注释

DBRefs are similar to manual references in the sense that they also contain the referenced document’s _id. However, they contain the referenced document’s collection in the $ref field and optionally its database as well in the $db field.


The advantage of this over manual references is that it clarifies which collection we are referencing.


4. Application Setup


4.1. Dependency


Firstly, we need to add the required dependencies to use MongoDB with Spring Boot.

首先,我们需要添加所需的依赖项,以便在Spring Boot中使用MongoDB。

Let’s add spring-boot-starter-data-mongodb to our pom.xml:



4.2. Configuration


Now, we set up the connection by adding the following configuration to the application.properties file:



Let’s run the application to test whether we can connect to the database. We should see a message similar to this in the logs:


Opened connection [connectionId{localValue:2, serverValue:37}] to localhost:27017

This means that the application could successfully connect to MongoDB.


4.3. Collections


In MongoDB, we use collections to store individual documents. They are the counterpart of tables in relational databases.

在MongoDB中,我们使用 collections来存储单个文档。它们与关系型数据库中的表相对应。

In this example, we’ll work with three different data types: Person, Dog, and Cat. We’ll connect persons to their pets.


Let’s create the collections in the database with some data. We can use Mongo Express for this, but any other tool would work as well.

让我们用一些数据在数据库中创建集合。我们可以使用Mongo Express来做这件事,但任何其他工具也可以工作。

Firstly, let’s create a database named person_database and create two collections inside it named Dog and Cat. We’ll insert one document into each one. To simplify, both of them will have only one property: the pet’s name.


Let’s insert this document into the Dog collection:


    _id: ObjectID("622112d71f9dac417b84227d"), 
    name: "Max"

Then, let’s insert this document into the Cat collection:


    _id: ObjectID("622112781f9dac417b84227b"),
    name: "Loki"

Now, let’s create the Person collection and insert a document into it:


    _id: ObjectId(),
    name: "Bob",
    pets: [
          "$ref": "Cat",
          "$id": "622112781f9dac417b84227b",
          "$db": ""
          "$ref": "Dog",
          "$id": "622112d71f9dac417b84227d",
          "$db": ""

We provide the pets as an array. The items of the array need to follow a specific format to be able to use them as DBRefs. We need to provide the name of the collection in the $ref property. In this case, it’s Cat and Dog. Then, we include the ID of the referenced documents. Lastly, we can optionally include a database name in the $db property if we would like to reference the collections from a different database.


5. Using the @DBRef Annotation


We can map the previously created collections to Java classes, similar to what we would do when working with a relational database.


To simplify, we won’t create separate classes for the Dog and Cat data types. Instead, we’ll use a Pet class that contains an ID and a name:


public class Pet {
    private String id;
    private String name;

    public String toString() {
        return "Pet [id=" + id + ", name=" + name + "]";

    // standard getters and setters

Now, we’ll create the Person class and include an association to the Pet class via @DBRef:


@Document(collection = "Person")
public class Person {

    private String id;
    private String name;

    private List<Pet> pets;

    public String toString() {
        return "Person [id=" + id + ", name=" + name + ", pets=" + pets + "]";

    // standard getters and setters

Next, let’s create a simple repository to be able to query data:


public interface PersonRepository extends MongoRepository<Person, String> {}

We’ll test everything by creating an ApplicationRunner that executes a MongoDB query when we start the application. Let’s override the run() method and put a log statement so we can see the contents of the Person collection:

我们将通过创建一个ApplicationRunner来测试一切,当我们启动应用程序时,它会执行一个 MongoDB 查询。让我们重写run()方法,并放入一个日志语句,以便我们可以看到Person集合的内容。

public void run(ApplicationArguments args) throws Exception {
    logger.info("{}", personRepository.findAll());

This produces a log output similar to this because we have overridden the toString() method in our entity classes:


com.baeldung.mongodb.dbref.DbRefTester : [Person [id=62249c5c7ffe83c50ad12700, name=Bob, pets=[Pet [id=622112781f9dac417b84227b, name=Loki], Pet [id=622112d71f9dac417b84227d, name=Max]]]]

This means that we successfully read and joined documents from different collections.


5.1. Reference a Different Database


The @DBRef annotation accepts two parameters. One of them is the db parameter, which can be used to reference documents in other databases.


This is optional, which means that the application looks for referenced documents in the same database if we don’t provide this value.


In our case, if the Cat or Dog would reside in a different database named pet_database, we would need to change the annotation to this: @DBRef(db = “pet_database”).

在我们的案例中,如果将驻留在一个名为pet_database>的不同数据库中,我们将需要把注释改为这样。@DBRef(db = “pet_database”)

5.2. Lazy Loading


The other parameter accepted by the annotation is called lazy. This is a boolean value that determines if the referenced documents should be loaded lazily or not.


By default, it is false, which means that the references will be loaded eagerly when we query the main entity. If we turn this feature on, the referenced documents will not be loaded until they are accessed first.


6. Conclusion


In this article, we compared MongoDB manual references with Spring Data MongoDB @DBRef. We created three collections and connected them with this annotation. We created a Spring Boot application to query these collections using a MongoRepository and displayed the related documents.

在这篇文章中,我们将MongoDB的手动引用与Spring Data MongoDB的@DBRef进行了比较。我们创建了三个集合,并用这个注解将它们连接起来。我们创建了一个Spring Boot应用程序,使用MongoRepository查询这些集合,并显示相关文档。

As always, the source code for the examples is available over on GitHub.