SoFunction
Updated on 2025-04-05

Implementation of SpringBoot Integrated MongoDB

1. Introduction to MongoDB

MongoDB is an open source, high-performance, schema-free document-based database, which belongs to a NoSQL database. MongoDB was designed to simplify development and facilitate scalability, while providing scalable, high-performance data storage solutions.

Here are some key features of MongoDB:

  • Documentation-oriented: Data in MongoDB is stored as documents, which are collections of key-value pairs, similar to JSON objects but use the BSON (Binary JSON) format, which allows it to store complex data types.
  • Schema-less: Unlike relational databases, MongoDB does not need to pre-defined fixed table structures, and each document can have different fields and data types.
  • High availability and scalability: MongoDB supports automatic sharding, which helps to scale horizontally, can handle large amounts of data and high concurrent access.
  • Rich query language:MongoDB provides powerful query capabilities, and its syntax is close to an object-oriented query language and supports complex query operations, including sorting, aggregation, etc.
  • Index support: In order to speed up querying, MongoDB supports indexing of fields, including single-field indexes, composite indexes, geospatial indexes, etc.
  • Copy and fault tolerance: Through replica sets (replica set), MongoDB can realize redundant data storage, improving system reliability and fault tolerance.
  • Easy to use and integrate: MongoDB provides drivers in a variety of programming languages ​​to facilitate developers to develop applications, and has graphical management tools such as Compass, Navicat, Studio 3T, etc. to assist in database management and maintenance.
  • Community and support: As a widely used database system, MongoDB has an active community and official commercial support services.

MongoDB is designed to meet the needs of modern applications, especially those that need to process large amounts of unstructured or semi-structured data, such as content management systems, real-time analytics, mobile application backends, etc. Due to its flexibility and performance advantages, MongoDB has become one of the preferred database solutions for many developers and businesses.

2. MongoDB installation

Linux installation
Download MongoDB Community Server
Download address:/try/download/community

Start MongoDB Server after decompression

#Create dbpath and logpathmkdir -p /mongodb/data /mongodb/log  
#Enter the mongodb directory and start the mongodb servicebin/mongod --port=27017 --dbpath=/mongodb/data --logpath=/mongodb/log/

3. SpringBoot integrates MongoDB

3.1. Environmental preparation

1. Introduce dependencies

<dependency>
    <groupId></groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

The complete dependency is as follows:

 <parent>
    <groupId></groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.</version>
  </parent>

  <properties>
    <>UTF-8</>
    <>1.8</>
  </properties>

  <dependencies>
    <dependency>
      <groupId></groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
      <groupId></groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId></groupId>
      <artifactId>commons-lang3</artifactId>
      <version>3.9</version>
    </dependency>

    <dependency>
      <groupId></groupId>
      <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>
    
    <dependency>
      <groupId></groupId>
      <artifactId>lombok</artifactId>
    </dependency>

    <dependency>
      <groupId></groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.68</version>
    </dependency>
  </dependencies>

2. Configuration

# MongoDB
 = 127.0.0.1
 = 27017
 = test
-index-creation = true

# Or use the uri method directly#=mongodb://user:[email protected]:27017/test?authSource=admin

# Print mongoDB log=DEBUG
=DEBUG

Please refer to the documentation for connection configuration/zh-cn/docs/manual/reference/connection-string/

3.2. Document operation

1. Add a new entity

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Document(collection = "person") // Specify the collection namepublic class Person {
    @Id  // Map the _id in the document    private Long id;
    private String name;
    private Integer age;
}

2. Add a collection document

Inject MongoTemplate during collection operation

@SpringBootTest(classes = )
@RunWith()
public class InsertTests {
    
    @Resource
    private MongoTemplate mongoTemplate;

    @Test
    public void testInsert() {
        Person person = ().id(2L).name("river").age(18).build();
        (person);

        // If there is any, modify it; if there is no, insert it        (().id(2L).name("zhangsan").age(28).build());

        // Batch writing        List&lt;Person&gt; persons = new ArrayList&lt;&gt;();
        for (int i = 100; i &lt;= 150; i++) {
            person = ().id((i)).name("lisi" + i).age(i).build();
            (person);
        }
        (persons);
    }
}

When inserting data: The _id inserted in insert cannot be duplicated, otherwise a DuplicateKeyException will be reported to prompt the primary key to be duplicated; save updates the existing data;
During batch operation: insertAll can insert all data at one time, which is more efficient; save needs to traverse all data, insert or update at one time, which is less efficient.

3. Query the collection document

@Slf4j
@SpringBootTest(classes = )
@RunWith()
public class QueryTests {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Test
    public void find() {
        // Query all document data in the collection        List&lt;Person&gt; personList = ();
        ("Query results:{}", personList);

        // Query the ID document data specified in the collection        Person byId = (1L, );
        ("Query results:{}", ());

        // Query the document data that meets the conditions and return the first piece of data according to the conditions        Query query = new Query(("name").is("river"));
        Person result = (query, );
        ("Query results:{}", result);

        // Query all documents that meet the conditions based on the conditions        query = new Query(("age").gt(18));
        List&lt;Person&gt; list = (query, );
        ("Query results:{}", list);

        // Create a query object and add the conditional object to it        Criteria criteria = ("age").gt(18).lte(30);
        query = new Query(criteria);
        list = (query, );
        ("Query results:{}", list);

        Criteria name = ("name").is("zhangsan");
        Criteria age = ("age").is(18);
        // Create a condition object and AND association the above conditions        criteria = new Criteria().andOperator(name, age);
        query = new Query(criteria);
        list = (query, );
        ("Query results:{}", list);

        // Starting from line 5, query 3 data to return        query = new Query(("age").is("20"))
                .with(("id"))
                .limit(3).skip(5);
        list = (query, );
        ("Query results:{}", list);
    }
}

Criteria is an interface for standard query. It can refer to statically combine multiple conditions, so that multiple method queries can be easily connected, making it easier for us to operate query statements.

4. Update the collection document

@Slf4j
@SpringBootTest(classes = )
@RunWith()
public class UpdateTests {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Test
    public void update() {
        Person person = (1L, );
        ("wangwu");
        (person);

        Query query = new Query(("id").is(1L));
        // Modify content        Update update = new Update().set("name", "lisi");
        UpdateResult updateResult = (query, update, );
// // Only the first record that meets the criteria is updated//        UpdateResult updateResult = (query, update, );

        // Insert data if there is no record that meets the criteria// // ("id",11); // Specify _id//        updateResult = (query, update, );

        // Return the number of modified records        ("updateResult: {}", ());

    }
}

If the updated result is the same as the previous update result, return 0.
updateFirst() only updates the first record that meets the condition
updateMulti() Update all records that meet the criteria
upsert() inserts data if there is no record that meets the criteria.

5. Delete the collection document

@Slf4j
@SpringBootTest(classes = )
@RunWith()
public class DeleteTests {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Test
    public void delete() {
        // Delete records with id 1        Query query = new Query(("id").is(1L));
        DeleteResult remove = (query, );
        ("The number of deleted items is:{}", ());

        // Delete a single document that meets the criteria and return the deleted document        query = new Query(("id").is(2L));
        Person per = (query, );
        ("Deleted documents: {}", per);
    }
}

3.3. Remove the _class attribute

When writing to a document using MongoTemplate, the _class attribute will be automatically added to the document. Generally, there is no need to use the _class attribute, and you can configure to remove the _class attribute.

@Configuration
public class MongoConfig {

    @Bean("mongoTemplate")
    public MongoTemplate mongoTemplate(MongoDbFactory mongoDbFactory, MongoMappingContext mongoMappingContext) {
        DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDbFactory);
        MappingMongoConverter mappingMongoConverter = new MappingMongoConverter(dbRefResolver, mongoMappingContext);
        // Remove the _class field        (new DefaultMongoTypeMapper(null));
        return new MongoTemplate(mongoDbFactory, mappingMongoConverter);
    }
}

This is the end of this article about the implementation of SpringBoot Integration MongoDB. For more related SpringBoot Integration MongoDB content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!