MongoDB 使用

发布于:2024-04-29 ⋅ 阅读:(24) ⋅ 点赞:(0)

一、引用依赖包

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

二、 配置文件配置mongodb资料

MongoDB连接信息
spring.data.mongodb.host = 192.168.120.128
spring.data.mongodb.port = 27017
spring.data.mongodb.database = m1
spring.data.mongodb.auto-index-creation = true

 三、 准备对象Person

package com.yy.model;

import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;

import java.time.LocalDateTime;

@Document(collection = "person") // 指定集合名称,就是类似mysql的表,如果不指定就以类名称作为集合名称
@Data
public class Person {
    @Id // 文档id, 很重要,类似mysql表的主键
    private Long id;
    private String name;
    private Integer age;
    /**
     * 创建一个10秒之后文档自动删除的索引 结合 spring.data.mongodb.auto-index-creation = true 一起使用
     创建一个10秒之后文档自动删除, 类似 redis ttl
     注意:这个字段必须是date类型或者是一个包含date类型值的数组字段,一般我们使用date类型;

     */
    @Indexed(expireAfterSeconds=10)
    private LocalDateTime createTime;
}

 

四、 编写测试类进行测试

 

1 新增

package com.yy;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.yy.model.Person;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;

import java.util.ArrayList;
import java.util.List;

@SpringBootTest
class InsertAppTests {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 插入文档
     */
    @Test
    void insert() {
        Person person =new Person();
        person.setId(20530712L);
        person.setName("张三");
        person.setAge(26);
        mongoTemplate.insert(person);

    }
    /**
     * 自定义集合,插入文档
     */
    @Test
    public void insertCustomCollection() throws Exception {
        Person person =new Person();
        person.setId(20530712L);
        person.setName("张三");
        person.setAge(26);
        person.setCreateTime(LocalDateTimeUtil.now());
        mongoTemplate.insert(person, "custom_person");
    }
    /**
     * 批量插入文档
     */
    @Test
    public void insertBatch() throws Exception {
        List<Person> personList = new ArrayList<>();
        for (int i = 10; i < 15 ; i++) {
            Person person =new Person();
            person.setId((long) i);
            person.setName("张三"+i);
            person.setAge(26);
            person.setCreateTime(LocalDateTimeUtil.now());
            personList.add(person);

        }

        //mongoTemplate.insert(personList, "custom_person");
        mongoTemplate.insertAll(personList);
    }
    /**
     * 存储文档,如果没有插入,否则更新
     * 在存储文档的时候会通过主键 ID 进行判断,如果存在就更新,否则就插入
     */
    @Test
    public void save() throws Exception {
        Person person =new Person();
        person.setId(1L);
        person.setName("张三33");
        person.setAge(26);
        person.setCreateTime(LocalDateTimeUtil.now());
        mongoTemplate.save(person);
    }

}

 2 修改

package com.yy;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.mongodb.client.result.UpdateResult;
import com.yy.model.Person;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.List;

@SpringBootTest
class UpdateAppTests {
    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 更新文档,匹配查询到的文档数据中的第一条数据
     * @throws Exception
     */
    @Test
    public void update1() throws Exception {
        Person person = new Person();
        person.setName("张三7777"); // 示例名称

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

        //更新值
        Update update= new Update().set("name", person.getName()).set("age", 32);

        //更新查询满足条件的文档数据(第一条)
        UpdateResult result =mongoTemplate.updateFirst(query, update, Person.class);
        System.out.println("更新条数:" + result.getMatchedCount());
    }
    /**
     * 更新文档,匹配查询到的文档数据中的所有数据
     */
    @Test
    public void updateMany() throws Exception {

        //更新年龄大于等于32的人
        Query query= new Query(Criteria.where("age").gte(18));

        //更新姓名为 “我成人了”
        Update update= new Update().set("name", "我成人了");

        //更新查询满足条件的文档数据(全部)
        UpdateResult result = mongoTemplate.updateMulti(query, update, Person.class);
        System.out.println("更新条数:" + result.getMatchedCount());
    }

}

3  删除

package com.yy;

import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import com.yy.model.Person;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@SpringBootTest
class RemoveAppTests {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 删除符合条件的所有文档
     */
    @Test
    public void remove() throws Exception {
        //删除年龄小于18的所有人
        Query query = new Query(Criteria.where("age").lt(18));
        DeleteResult result = mongoTemplate.remove(query, Person.class);
        System.out.println("删除条数:" + result.getDeletedCount());
    }

    /**
     * 删除符合条件的单个文档,并返回删除的文档
     */
    @Test
    public void findAndRemove() throws Exception {

        Query query = new Query(Criteria.where("id").is(1L));
        Person result = mongoTemplate.findAndRemove(query, Person.class);
        System.out.println("删除的文档数据:" + result);
    }

    /**
     * 删除符合条件的所有文档,并返回删除的文档
     */
    @Test
    public void findAllAndRemove() throws Exception {

        // 使用 in 删除 符合条件的多条文档,并返回
        Query query = new Query(Criteria.where("id").in(1,2,3,4));
        List<Person> result = mongoTemplate.findAllAndRemove(query, Person.class);
        System.out.println("删除的文档数据:" + result.toString());
    }

}

4 查询

package com.yy;

import com.mongodb.client.result.DeleteResult;
import com.yy.model.Person;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Arrays;
import java.util.List;

@SpringBootTest
class SelectAppTests {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查询集合中的全部文档数据
     */
    @Test
    public void findAll()  {
        List<Person> result = mongoTemplate.findAll(Person.class);
        System.out.println("查询结果:" + result.toString());
    }

    /**
     * 查询集合中指定的ID文档数据
     */
    @Test
    public void findById() {
        long id = 2L;
        Person result = mongoTemplate.findById(id, Person.class);
        System.out.println("查询结果:" + result.toString());
    }
    /**
     * 根据条件查询集合中符合条件的文档,返回第一条数据
     */
    @Test
    public void findOne() {
        Query query = new Query(Criteria.where("name").is("张三3"));
        Person result = mongoTemplate.findOne(query, Person.class);
        System.out.println("查询结果:" + result.toString());
    }

    /**
     * 根据条件查询所有符合条件的文档
     */
    @Test
    public void findByCondition() {

        Query query = new Query(Criteria.where("age").gt(18));
        List<Person> result = mongoTemplate.find(query, Person.class);
        System.out.println("查询结果:" + result.toString());
    }
    /**
     * 根据【AND】关联多个查询条件,查询集合中所有符合条件的文档数据
     */
    @Test
    public void findByAndCondition() {
        // 创建条件
        Criteria name = Criteria.where("name").is("张三");
        Criteria age = Criteria.where("age").is(18);
        // 创建条件对象,将上面条件进行 AND 关联
        Criteria criteria = new Criteria().andOperator(name, age);
        // 创建查询对象,然后将条件对象添加到其中
        Query query = new Query(criteria);
        List<Person> result = mongoTemplate.find(query, Person.class);
        System.out.println("查询结果:" + result.toString());
    }
    /**
     * 根据【OR】关联多个查询条件,查询集合中的文档数据
     */
    @Test
    public void findByOrCondition() {
        // 创建条件
        Criteria criteriaUserName = Criteria.where("name").is("张三");
        Criteria criteriaPassWord = Criteria.where("age").is(22);
        // 创建条件对象,将上面条件进行 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());
    }
    /**
     * 根据【IN】关联多个查询条件,查询集合中的文档数据
     */
    @Test
    public void findByInCondition() {
        // 设置查询条件参数
        List<Long> ids = Arrays.asList(1L, 2L, 3L);
        // 创建条件
        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());
    }

    /**
     * 根据【逻辑运算符】查询集合中的文档数据
     */
    @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());
    }
    /**
     * 根据【正则表达式】查询集合中的文档数据
     */
    @Test
    public void findByRegex() {
        // 设置查询条件参数
        String regex = "^张";
        Criteria criteria = Criteria.where("name").regex(regex);
        // 创建查询对象,然后将条件对象添加到其中
        Query query = new Query(criteria);
        List<Person> result = mongoTemplate.find(query, Person.class);
        System.out.println("查询结果:" + result.toString());
    }

    /**
     * 根据条件查询集合中符合条件的文档,获取其文档列表并排序
     */
    @Test
    public void findByConditionAndSort() {
        Query query = new Query(Criteria.where("name").is("张三")).with(Sort.by("age"));
        List<Person> result = mongoTemplate.find(query, Person.class);
        System.out.println("查询结果:" + result.toString());
    }

    /**
     * 根据单个条件查询集合中的文档数据,并按指定字段进行排序与限制指定数目
     */
    @Test
    public void findByConditionAndSortLimit() {
        String userName = "张三";
        //从表中查询到的“张三”的数据的第5行开始,继续往下查询3条数据返回
        Query query = new Query(Criteria.where("name").is("张三"))
                .with(Sort.by("createTime"))
                .limit(3).skip(5);
        List<Person> result = mongoTemplate.find(query, Person.class);
        System.out.println("查询结果:" + result.toString());
    }
    /**
     * 统计集合中符合【查询条件】的文档【数量】
     */
    @Test
    public void countNumber() {
        // 设置查询条件参数
        String regex = "^张*";
        Criteria criteria = Criteria.where("name").regex(regex);
        // 创建查询对象,然后将条件对象添加到其中
        Query query = new Query(criteria);
        long count = mongoTemplate.count(query, Person.class);
        System.out.println("统计结果:" + count);
    }

}

5 索引

package com.yy;

import com.mongodb.client.ListIndexesIterable;
import com.mongodb.client.model.Indexes;
import org.bson.Document;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;

@SpringBootTest
class IndexAppTests {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 创建升序索引
     */
    @Test
    public void createAscendingIndex() {
        // 设置字段名称
        String field = "age";
        // 创建索引
        mongoTemplate.getCollection("person").createIndex(Indexes.descending(field));
    }

    /**
     * 根据索引名称移除索引
     */
    @Test
    public void removeIndex() {
        // 设置字段名称
        String field = "age_1";
        // 删除索引
        mongoTemplate.getCollection("person").dropIndex(field);
    }


    /**
     * 查询集合中所有的索引
     */
    @Test
    public void getIndexAll() {
        // 获取集合中所有列表
        ListIndexesIterable<Document> indexList =   mongoTemplate.getCollection("person").listIndexes();
        // 获取集合中全部索引信息
        for (org.bson.Document document : indexList) {
            System.out.println("索引列表:" + document);
        }
    }




}