SpringBoot integrates MongoDB to realize the addition, deletion, modification and query of data!

1. Introduction

There are three more important terms in MongoDB: database, collection, document !

  • Database (Database) : Like relational databases, each database has its own user permissions, and different project groups can use different databases

  • Collection: A collection refers to a document group (similar to the concept of a table in Mysql), which can store many documents

  • Document (Document) : Document is the most basic data unit in MongoDB. It consists of key-value pairs, similar to JSON format, and can store different fields. The values ​​of fields can include other documents, arrays, and document arrays

If you understand these three nouns, you can basically get started. Today we take the integration of MongoDB with SpringBoot as an example to realize the addition, deletion, modification and query of data.

Without further ado, let's start rolling!

2. Code practice

2.1. Create a SpringBoot project and add the MongoDB dependency package

<!-- 引入springboot -->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.0.RELEASE</version>
</parent>

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

2.2. Add configuration file

Add mongodb related configuration in the application.properties file!

#配置数据库连接地址
spring.data.mongodb.uri=mongodb://userName:[email protected]:27017/dbName

Related parameter description:

  • userName: Indicates the user name, which can be filled in according to the actual situation

  • password: Indicates the user password, which can be filled in according to the actual situation

  • dbName: Indicates the database, which can be customized, and will be automatically created when the data is initialized

2.3. Create entity classes

Create an entity class Person , where the annotation @Document(collection="persons") indicates that the collection name corresponding to the current entity class is persons , which is similar to the table name in a relational database.

The annotation @Id indicates the current field, which belongs to the primary key type in the collection structure.

/**
 * 使用@Document注解指定集合名称
 */
@Document(collection="persons")
public class Person implements Serializable {
    private static final long serialVersionUID = -3258839839160856613L;

    /**
     * 使用@Id注解指定MongoDB中的 _id 主键
     */
    @Id
    private Long id;

    private String userName;

    private String passWord;

    private Integer age;

    private Date createTime;

    //...get/set

    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", passWord='" + passWord + '\'' +
                ", age=" + age +
                ", createTime=" + createTime +
                '}';
    }
}

2.4, operate MongoDB

There are two ways for Springboot to operate MongoDB.

  • The first method is to use the JPA method officially recommended by Springboot. This method of operation is simple to use but less flexible.

  • The second method is to use Spring Data MongoDB to operate MongoDB based on the MongoTemplate operation class encapsulated by MongoDB's official Java API. This method is very flexible and can meet most of the needs.

This article will introduce the second way!

2.5. Insert document

MongoTemplate provides the insert() method for inserting documents, the sample code is as follows:

  • for inserting documents

When the collection name is not specified, the collection name in the @Document annotation will be taken
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 插入文档
     * @throws Exception
     */
    @Test
    public void insert() throws Exception {
        Person person =new Person();
        person.setId(1l);
        person.setUserName("张三");
        person.setPassWord("123456");
        person.setCreateTime(new Date());
        mongoTemplate.insert(person);
    }
}
  • Custom collection name, insert document

@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 自定义集合,插入文档
     * @throws Exception
     */
    @Test
    public void insertCustomCollection() throws Exception {
        Person person =new Person();
        person.setId(1l);
        person.setUserName("张三");
        person.setPassWord("123456");
        person.setCreateTime(new Date());
        mongoTemplate.insert(person, "custom_person");
    }
}
  • Custom collection, batch insert documents

If you use batch insert documents, you must specify the collection name
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 自定义集合,批量插入文档
     * @throws Exception
     */
    @Test
    public void insertBatch() throws Exception {
        List<Person> personList = new ArrayList<>();
        Person person1 =new Person();
        person1.setId(10l);
        person1.setUserName("张三");
        person1.setPassWord("123456");
        person1.setCreateTime(new Date());
        personList.add(person1);

        Person person2 =new Person();
        person2.setId(11l);
        person2.setUserName("李四");
        person2.setPassWord("123456");
        person2.setCreateTime(new Date());
        personList.add(person2);

        mongoTemplate.insert(personList, "custom_person");
    }
}

2.6. Store documents

MongoTemplate provides the save() method for storing documents.

When storing a document, it will be judged by the primary key ID. If it exists, it will be updated, otherwise it will be inserted. The sample code is as follows:

  • store document, if not inserted, otherwise update by primary key id

@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 存储文档,如果没有插入,否则更新
     * @throws Exception
     */
    @Test
    public void save() throws Exception {
        Person person =new Person();
        person.setId(13l);
        person.setUserName("八八");
        person.setPassWord("123456");
        person.setAge(40);
        person.setCreateTime(new Date());
        mongoTemplate.save(person);
    }
}
  • Custom collections to store documents

@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 自定义集合,存储文档
     * @throws Exception
     */
    @Test
    public void saveCustomCollection() throws Exception {
        Person person =new Person();
        person.setId(1l);
        person.setUserName("张三");
        person.setPassWord("123456");
        person.setCreateTime(new Date());
        mongoTemplate.save(person, "custom_person");
    }
}

2.7. Update documents

MongoTemplate provides updateFirst() and updateMulti() methods for updating documents. The sample code is as follows:

  • Update the document to match the first piece of data in the queried document data

@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 更新文档,匹配查询到的文档数据中的第一条数据
     * @throws Exception
     */
    @Test
    public void updateFirst() throws Exception {
        //更新对象
        Person person =new Person();
        person.setId(1l);
        person.setUserName("张三123");
        person.setPassWord("123456");
        person.setCreateTime(new Date());

        //更新条件
        Query query= new Query(Criteria.where("id").is(person.getId()));

        //更新值
        Update update= new Update().set("userName", person.getUserName()).set("passWord", person.getPassWord());
        //更新查询满足条件的文档数据(第一条)
        UpdateResult result =mongoTemplate.updateFirst(query,update, Person.class);
        if(result!=null){
            System.out.println("更新条数:" + result.getMatchedCount());
        }
    }
}
  • Update the document to match all the data in the queried document data

@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 更新文档,匹配查询到的文档数据中的所有数据
     * @throws Exception
     */
    @Test
    public void updateMany() throws Exception {
        //更新对象
        Person person =new Person();
        person.setId(1l);
        person.setUserName("张三");
        person.setPassWord("123456");
        person.setCreateTime(new Date());

        //更新条件
        Query query= new Query(Criteria.where("id").is(person.getId()));

        //更新值
        Update update= new Update().set("userName", person.getUserName()).set("passWord", person.getPassWord());
        //更新查询满足条件的文档数据(全部)
        UpdateResult result = mongoTemplate.updateMulti(query, update, Person.class);
        if(result!=null){
            System.out.println("更新条数:" + result.getMatchedCount());
        }
    }
}

2.8. Delete documents

MongoTemplate provides remove() , findAndRemove() and findAllAndRemove() methods for deleting documents. The sample code is as follows:

  • Delete all documents matching the criteria

@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 更新文档,匹配查询到的文档数据中的所有数据
     * @throws Exception
     */
    @Test
    public void updateMany() throws Exception {
        //更新对象
        Person person =new Person();
        person.setId(1l);
        person.setUserName("张三");
        person.setPassWord("123456");
        person.setCreateTime(new Date());

        //更新条件
        Query query= new Query(Criteria.where("id").is(person.getId()));

        //更新值
        Update update= new Update().set("userName", person.getUserName()).set("passWord", person.getPassWord());
        //更新查询满足条件的文档数据(全部)
        UpdateResult result = mongoTemplate.updateMulti(query, update, Person.class);
        if(result!=null){
            System.out.println("更新条数:" + result.getMatchedCount());
        }
    }
}
  • Delete a single document matching the criteria, and return the deleted document

@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 删除符合条件的单个文档,并返回删除的文档
     * @throws Exception
     */
    @Test
    public void findAndRemove() throws Exception {
        Person person =new Person();
        person.setId(1l);
        person.setUserName("张三");
        person.setPassWord("123456");
        person.setCreateTime(new Date());

        Query query = new Query(Criteria.where("id").is(person.getId()));
        Person result = mongoTemplate.findAndRemove(query, Person.class);
        System.out.println("删除的文档数据:" + result.toString());
    }
}
  • Delete all documents matching the criteria, and return the deleted documents

@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 删除符合条件的所有文档,并返回删除的文档
     * @throws Exception
     */
    @Test
    public void findAllAndRemove() throws Exception {
        Person person =new Person();
        person.setId(1l);
        person.setUserName("张三");
        person.setPassWord("123456");
        person.setCreateTime(new Date());

        Query query = new Query(Criteria.where("id").is(person.getId()));
        List<Person> result = mongoTemplate.findAllAndRemove(query, Person.class);
        System.out.println("删除的文档数据:" + result.toString());
    }
}

2.9. Query documents

MongoTemplate provides a lot of document query methods, the most used in daily development is the find() method, the sample code is as follows:

  • Query all document data in the collection

@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查询集合中的全部文档数据
     * @throws Exception
     */
    @Test
    public void findAll() throws Exception {
        List<Person> result = mongoTemplate.findAll(Person.class);
        System.out.println("查询结果:" + result.toString());
    }
}
  • Query the specified ID document data in the collection

@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查询集合中指定的ID文档数据
     * @throws Exception
     */
    @Test
    public void findById() {
        long id = 1l;
        Person result = mongoTemplate.findById(id, Person.class);
        System.out.println("查询结果:" + result.toString());
    }
}
  • Query the qualified documents in the collection according to the conditions, and return the first piece of data

@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 根据条件查询集合中符合条件的文档,返回第一条数据
     */
    @Test
    public void findOne() {
        String userName = "张三";
        Query query = new Query(Criteria.where("userName").is(userName));
        Person result = mongoTemplate.findOne(query, Person.class);
        System.out.println("查询结果:" + result.toString());
    }
}
  • Query for eligible documents in a collection based on conditions

@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 根据条件查询集合中符合条件的文档
     */
    @Test
    public void findByCondition() {
        String userName = "张三";
        Query query = new Query(Criteria.where("userName").is(userName));
        List<Person> result = mongoTemplate.find(query, Person.class);
        System.out.println("查询结果:" + result.toString());
    }
}
  • Query the document data in the collection by associating multiple query conditions according to [AND]

@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 根据【AND】关联多个查询条件,查询集合中的文档数据
     */
    @Test
    public void findByAndCondition() {
        // 创建条件
        Criteria criteriaUserName = Criteria.where("userName").is("张三");
        Criteria criteriaPassWord = Criteria.where("passWord").is("123456");
        // 创建条件对象,将上面条件进行 AND 关联
        Criteria criteria = new Criteria().andOperator(criteriaUserName, criteriaPassWord);
        // 创建查询对象,然后将条件对象添加到其中
        Query query = new Query(criteria);
        List<Person> result = mongoTemplate.find(query, Person.class);
        System.out.println("查询结果:" + result.toString());
    }
}
  • Query the document data in the collection by associating multiple query conditions with [OR]

@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 根据【OR】关联多个查询条件,查询集合中的文档数据
     */
    @Test
    public void findByOrCondition() {
        // 创建条件
        Criteria criteriaUserName = Criteria.where("userName").is("张三");
        Criteria criteriaPassWord = Criteria.where("passWord").is("123456");
        // 创建条件对象,将上面条件进行 OR 关联
        Criteria criteria = new Criteria().orOperator(criteriaUserName, criteriaPassWord);
        // 创建查询对象,然后将条件对象添加到其中
        Query query = new Query(criteria);
        List<Person> result = mongoTemplate.find(query, Person.class);
        System.out.println("查询结果:" + result.toString());
    }
}
  • Query the document data in the collection by associating multiple query conditions according to [IN]

@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 根据【IN】关联多个查询条件,查询集合中的文档数据
     */
    @Test
    public void findByInCondition() {
        // 设置查询条件参数
        List<Long> ids = Arrays.asList(1l, 10l, 11l);
        // 创建条件
        Criteria criteria = Criteria.where("id").in(ids);
        // 创建查询对象,然后将条件对象添加到其中
        Query query = new Query(criteria);
        List<Person> result = mongoTemplate.find(query, Person.class);
        System.out.println("查询结果:" + result.toString());
    }
}
  • Query the document data in the collection according to [logical operators]

@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 根据【逻辑运算符】查询集合中的文档数据
     */
    @Test
    public void findByOperator() {
        // 设置查询条件参数
        int min = 20;
        int max = 35;
        Criteria criteria = Criteria.where("age").gt(min).lte(max);
        // 创建查询对象,然后将条件对象添加到其中
        Query query = new Query(criteria);
        List<Person> result = mongoTemplate.find(query, Person.class);
        System.out.println("查询结果:" + result.toString());
    }
}
  • Query the document data in the collection according to [regular expression]

@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 根据【正则表达式】查询集合中的文档数据
     */
    @Test
    public void findByRegex() {
        // 设置查询条件参数
        String regex = "^张*";
        Criteria criteria = Criteria.where("userName").regex(regex);
        // 创建查询对象,然后将条件对象添加到其中
        Query query = new Query(criteria);
        List<Person> result = mongoTemplate.find(query, Person.class);
        System.out.println("查询结果:" + result.toString());
    }
}
  • Query the qualified documents in the collection according to the conditions, get the list of documents and sort them

@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 根据条件查询集合中符合条件的文档,获取其文档列表并排序
     */
    @Test
    public void findByConditionAndSort() {
        String userName = "张三";
        Query query = new Query(Criteria.where("userName").is(userName)).with(Sort.by("age"));
        List<Person> result = mongoTemplate.find(query, Person.class);
        System.out.println("查询结果:" + result.toString());
    }
}
  • Query the document data in the collection according to a single condition, and sort and limit the specified number by the specified field

@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {

    @Autowired
    private MongoTemplate mongoTemplate;

   /**
     * 根据单个条件查询集合中的文档数据,并按指定字段进行排序与限制指定数目
     */
    @Test
    public void findByConditionAndSortLimit() {
        String userName = "张三";
        //从第一行开始,查询2条数据返回
        Query query = new Query(Criteria.where("userName").is(userName)).with(Sort.by("createTime")).limit(2).skip(1);
        List<Person> result = mongoTemplate.find(query, Person.class);
        System.out.println("查询结果:" + result.toString());
    }
}
  • Count the [number] of documents that meet the [query condition] in the collection

@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {

    @Autowired
    private MongoTemplate mongoTemplate;

   /**
     * 统计集合中符合【查询条件】的文档【数量】
     */
    @Test
    public void countNumber() {
        // 设置查询条件参数
        String regex = "^张*";
        Criteria criteria = Criteria.where("userName").regex(regex);
        // 创建查询对象,然后将条件对象添加到其中
        Query query = new Query(criteria);
        long count = mongoTemplate.count(query, Person.class);
        System.out.println("统计结果:" + count);
    }
}

3.0, index management

In all databases, the temporary location of the index is very important. For example, when you retrieve a data table with millions of data, if there is no index, the query efficiency will be extremely slow. The same is true for MongoDB.

Examples are as follows:

  • Create an ascending index

@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 创建升序索引
     */
    @Test
    public void createAscendingIndex() {
        // 设置字段名称
        String field = "userName";
        // 创建索引
        mongoTemplate.getCollection("persons").createIndex(Indexes.ascending(field));
    }
}
  • remove index

@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {

    @Autowired
    private MongoTemplate mongoTemplate;

   /**
     * 根据索引名称移除索引
     */
    @Test
    public void removeIndex() {
        // 设置字段名称
        String field = "userName";
        // 删除索引
        mongoTemplate.getCollection("persons").dropIndex(field);
    }
}
  • Query all indexes in the collection

@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {

    @Autowired
    private MongoTemplate mongoTemplate;

   /**
     * 查询集合中所有的索引
     */
    @Test
    public void getIndexAll() {
        // 获取集合中所有列表
        ListIndexesIterable<Document> indexList = mongoTemplate.getCollection("persons").listIndexes();
        // 获取集合中全部索引信息
        for (Document document : indexList) {
            System.out.println("索引列表:" + document);
        }
    }
}
  • We can also create indexes by annotating entity classes

/**
 * 使用@Document注解指定集合名称
 */
@Document(collection="persons")
public class Person implements Serializable {
    private static final long serialVersionUID = -3258839839160856613L;

    /**
     * 使用@Id注解指定MongoDB中的 _id 主键
     */
    @Id
    private Long id;

    private String userName;

    private String passWord;

    private Integer age;

    /**
     * 创建一个5秒之后文档自动删除的索引
     */
    @Indexed(expireAfterSeconds=5)
    private Date createTime;

    //...get/set

    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", passWord='" + passWord + '\'' +
                ", age=" + age +
                ", createTime=" + createTime +
                '}';
    }
}

3.1. Introducing transactions in MongoDB

Single-node mongodb does not support transactions, and a MongoDB replication set needs to be built.
/**
 * 配置事务管理器
 *
 */
@Configuration
public class TransactionConfig {

    @Bean
    MongoTransactionManager transactionManager(MongoDatabaseFactory dbFactory) {
        return new MongoTransactionManager(dbFactory);
    }

}

Transaction service test!

@Service
public class TransactionExample {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Transactional(rollbackFor = Exception.class)
    public Object transactionTest(){
        Person person =new Person();
        person.setId(1l);
        person.setUserName("张三");
        person.setPassWord("123456");
        person.setCreateTime(new Date());
        Person newPerson = mongoTemplate.insert(person);
        // 测试抛出异常,观察数据是否进行回滚
        if(1 == 1){
            throw new RuntimeException("异常");
        }
        return newPerson;
    }
}

3. Summary

This article mainly focuses on the basic introduction of SpringBoot's integration of MongoDB to realize the addition, deletion, modification and query of data. If there is any wrong description, please restore the netizen's message and point it out!

In actual business scenarios, you may also need to use advanced queries such as aggregation functions. If you have such a need, you can visit the following address to obtain a more detailed introduction to the api document: MongoDB document query api introduction

Guess you like

Origin blog.csdn.net/qq_42003636/article/details/129286618