Make MongoDB CRUD taste like JPA

Keywords: Database MongoDB Spring

        The previous article introduced the operation of CRUD of MongoDB using MongoTemplate. Then, the previous article will continue to introduce the operation of CRUD of MongoDB using MongoRepository.

         To review the above articles, you can click the link to view the link   CRUD MongoDB using MongoTemplate

        Take a look at the simple description of MongoDB on the official website of MongoDB. The screenshot is shown below.

        In the previous article, when using MongoTemplate, you only need to inject it with @ Autowired. When using MongoRepository, you need to define a Repository interface and inherit MongoRepository.

        Next, let's introduce the usage of MongoRepository.

1, Introducing dependencies in SpringBoot

         Then, in the project of the previous article, use MongoRepository to complete the CRUD of MongoDB. It doesn't matter if you don't read the previous article using MongoTemplate to CRUD MongoDB. Just create a SpringBoot project, and then introduce the dependency coordinates of MongoDB in the POM file to integrate the class library operating MongoDB into the SpringBoot project. The relevant dependencies are as follows:


2, Add configuration

        After introducing the dependency, if the Maven project does not automatically download the dependency, you need to refresh it manually, and then add the address of MongoDB in the SpringBoot configuration file application.yml (or Just like using MySQL, provide a uri to tell the project. The configuration file is as follows:

      uri: mongodb://

        In the above uri, test specifies the database to be operated in our Demo.

3, Define corresponding MongoDB   Entity classes in Collections

        When operating mysql, we will define a corresponding entity class in the MySQL table in the project, and we also need to define a corresponding entity class to operate the MongoDB collection. Here, a Student's entity class is defined to operate as an entity class in the Demo. The definitions are as follows:

public class Student {

    private String id;
    private String name;
    private Integer age;
    private String email;

        Add the annotation @ Document on the entity class, and the name of the collection is given in @ Document. Annotation @ id will match this field with the field generated by MongoDB_ id.

        When operating MongoDB, you can operate through MongoTemplate or MongoRepository. The previous article introduced the CRUD of MongoTemplate to MongoDB. This time, we will introduce how to use MongoRepository to complete the CRUD operation of MongoDB.

         The above three steps are exactly the same as using MongoTemplate, but the following steps are slightly different.

4, Define a class that implements the MongoRepository interface

         This step is not available in MongoTemplate. We need to define a Repository interface to inherit the MongoRepository interface, similar to defining a Mapper or a Dao. The definition is as follows:

public interface StudentRepository extends MongoRepository<Student, String> {


         With this interface, we can operate Student documents in MongoDB database through it.

         Here is a brief introduction to MongoRepository   The interface inherits the PagingAndSortingRepository interface, which defines paging and sorting functions. The PagingAndSortingRepository interface inherits the CrudRepository interface, which defines a group of CRUD related methods. The inheritance diagram is as follows:

        Looking at the inheritance diagram above, does it have a familiar flavor? That is, the inheritance diagram of Spring Data Jpa is similar. Change MongoRepository to JpaRepository to observe the inheritance diagram, as shown below.

         It can be seen that the method of using Repository to operate MongoDB can also be used to operate MySQL database, and vice versa. If you use it to operate MySQL at ordinary times, it can be easily applied to MongoDB.

5, Using MongoRepository   Complete CRUD

         If the StudentRepository interface is defined, the class that needs to operate on students can be used as long as the StudentRepository is injected.

1. Inject StudentRepository into the usage class

        Create a test class and inject StudentRepository through @ Autowired. The code is as follows:

// Inject StudentRepository
private StudentRepository studentRepository;

2. Add operation

        If you have read the article "CRUD MongoDB using MongoTemplate", you can delete the data generated in the previous article first. The deletion method is as follows:

        First, select the test database, as shown in the following figure:

         Next, view the collection in the database, as shown in the following figure:

        Finally, delete the Student set, as shown in the following figure:

         Delete the original test data so that we have a clean environment for testing.

         After injecting StudentRepository, we can complete CRUD operation in the test class. First, we can complete the operation of adding data. The code is as follows:

 * Add operation
void create() {

    for (int i = 0; i < 10; i ++) {
        Student student = new Student();
        student.setName("zhangsan" + i);
        student.setAge(30 + i);
        student.setEmail(i + "");

        Student save =;


         You can insert data through the save method of StudentRepository.

        After executing the above test code, let's check the data we added through the MongoDB client. First use use to select the database, and then use show collections to view the collection under the test database. You can see that a Student collection is automatically created under the test database, as shown in the following figure.

        Before we execute the above save method, we have deleted the Student set and have not created the Student set again. After executing the above code, the Student collection is automatically created and 10 documents are inserted into the Student collection.

3. Query all records in the collection

        The operation of inserting document data has been completed above. Now find all of them through StudentRepository. The code is as follows:

 * Query all records in the table
void findAll() {
    List<Student> all = studentRepository.findAll();


        Through the findAll method of StudentRepository, you can query all documents under the specified collection.

        After executing the above code, all documents in the Student collection will be output on the console, as shown below.

Student(id=6153405a080b7946ca278b3e, name=zhangsan0, age=30,
Student(id=6153405a080b7946ca278b3f, name=zhangsan1, age=31,
Student(id=6153405a080b7946ca278b40, name=zhangsan2, age=32,
Student(id=6153405a080b7946ca278b41, name=zhangsan3, age=33,
Student(id=6153405a080b7946ca278b42, name=zhangsan4, age=34,
Student(id=6153405a080b7946ca278b43, name=zhangsan5, age=35,
Student(id=6153405a080b7946ca278b44, name=zhangsan6, age=36,
Student(id=6153405a080b7946ca278b45, name=zhangsan7, age=37,
Student(id=6153405a080b7946ca278b46, name=zhangsan8, age=38,
Student(id=6153405a080b7946ca278b47, name=zhangsan9, age=39,

        From the output, we can see that MongoDB generates an id for us. Through this id, we can uniquely determine a piece of data.

4. Query the specified document by id

        Usually, when we query a specified piece of data, we will query by id. when adding data, we can see that MongoDB automatically generates an id for us, named_ id, just pass the findById method of MongoRepository (MongoTemplate also has findById method) and pass in the corresponding id value to query the specified document. The code is as follows:

 * id query
void findById() {
    Student student = studentRepository.findById("6153405a080b7946ca278b3e").get();

        The findById of MongoRepository returns optional < Student >   Type. The Student type can be obtained through the get method.

5. Condition query

        MongoDB supports very powerful query function. Here you can simply complete a conditional query. The code is as follows:

 * Condition query
void findUserList() {
    // name = zhangsan0 and age = 30
    Student student = new Student();
    Example<Student> userExample = Example.of(student);
    List<Student> all = studentRepository.findAll(userExample);

         The above query is equivalent to the following SQL statement:

select * from student where name = 'zhangsan0' and age = 30

        In addition to building query criteria through Example, you can also query by defining an interface in StudentRepository. The above query is defined in StudentRepository. The code is as follows:

public interface StudentRepository extends MongoRepository<Student, String> {
    Student getStudentByNameAndAge(String name, Integer age);

        With the above definition, you can call it without implementing your own code. The calling method is as follows:

void findUserByCondition()
    Student zhangsan0 = studentRepository.getStudentByNameAndAge("zhangsan0", 30);


        The function of automatically generating query statements provided by Spring Data only needs to define the method name in the interface according to the agreed rules.

6. Fuzzy query

        The fuzzy query provided by MongoRepository can be completed by using ExampleMatcher and Example. The code is as follows:

 * Fuzzy query
void findLikeUserList() {
    // name like zhangsan and age = 30

    // Set fuzzy query matching rules
    ExampleMatcher matcher = ExampleMatcher

    Student student = new Student();


    Example<Student> studentExample = Example.of(student, matcher);

    List<Student> all = studentRepository.findAll(studentExample);


        Define fuzzy query rules in ExampleMatcher, and provide query conditions in Example to complete the function of fuzzy query. Similarly, fuzzy queries can also use the rules provided by Spring Data to automatically generate query statements, which will not be demonstrated here.

7. Paging query

        For paging query of data in MySQL, you generally need to pass in the page number and the number of records per page to the interface. Of course, you also need to pass in some query conditions. For MongoDB, the data passed into the interface is the same.

void findPageUserList() {
    // paging
    // 0 represents the first page
    Pageable pageable = PageRequest.of(1, 3);

    Page<Student> page = studentRepository.findAll(pageable);


         Paging query passed   Pageable, which is similar to MySQL's limit. In the above code, our page displays 3 items per page, and the current page is page 1. The first parameter of PageRequest.of is the number of pages. As long as the number of pages is passed, it will automatically calculate the number of records to get data from.

Student(id=6153405a080b7946ca278b41, name=zhangsan3, age=33,
Student(id=6153405a080b7946ca278b42, name=zhangsan4, age=34,
Student(id=6153405a080b7946ca278b43, name=zhangsan5, age=35,

        The total number of pages can be obtained by calling the getTotalPages method through the returned Page object.

8. Modify data

        When modifying data, first query the data, then set the value to be modified, and then update the data.

 * modify
void updateUser() {
    Student student = studentRepository.findById("6153405a080b7946ca278b41").get();


    Student save =;


        In the above code, the data can be updated by using the save method of MongoRepository. In the previous introduction, the save method is also used when inserting. When calling the save method, if the id in the entity class has a value, it will be updated. If there is no value, it will be inserted. The implementation source code is as follows:

public <S extends T> S save(S entity) {
    Assert.notNull(entity, "Entity must not be null!");
    return this.entityInformation.isNew(entity) ? this.mongoOperations.insert(entity, this.entityInformation.getCollectionName()) :, this.entityInformation.getCollectionName());

        You can see that isNew is used in the source code to determine whether it is an insert operation or an update operation.

        Next, check whether our data has been updated, as shown in the figure below.

        When updating a field, you can set which field to update.

9. Delete data

        The deleteById provided by MongoRepository can be directly used for deletion. The code is as follows:

 * Delete operation
void deleteUser(){

6, Summary

        MongoDB has been used more and more. It is suitable for storing a large number of data without fixed data structure. This article briefly introduces the CRUD operation of MongoDB by using MongoRepository. The previous article introduced   CRUD MongoDB using MongoTemplate   Content of the. You can learn by comparison.

The two article is organized into PDF file, and is answered in official account.   [mongo] download the documentation of spring boot integration operation MongoDB.

Posted by snizkorod on Tue, 12 Oct 2021 10:24:22 -0700