MongoDB的使用

一、Spring Boot集成MongoDB

1 引用依赖包

复制代码
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
 </dependency>

2 配置文件配置mongodb资料

复制代码
# MongoDB连接信息
spring.data.mongodb.host = 192.168.23.27
spring.data.mongodb.port = 27017
spring.data.mongodb.database = mall
#自动创建索引
spring.data.mongodb.auto-index-creation = true

3 准备对象Person

复制代码
@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;
}

二、Spring Boot操作MongoDB

1 新增文档

单个插入

java 复制代码
    @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 = 1; i < 5; 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 修改文档

java 复制代码
@Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 更新文档,匹配查询到的文档数据中的第一条数据
     * @throws Exception
     */
    @Test
    public void update1() throws Exception {
     
        //更新条件
        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 删除文档

java 复制代码
   @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));
        List<Person> result = mongoTemplate.findAllAndRemove(query, Person.class);
        System.out.println("删除的文档数据:" + result.toString());
    }

3 查询文档

1.原生查询

db.getCollection("my_person").find({ name: /^张/ ,name: /大/}) db.getCollection("my_person").find({ name: /\^张/,age:{lte:12}})

2.Java实现

java 复制代码
@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(10L, 11L, 12L);
        // 创建条件
        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);
    }

4 创建索引

java 复制代码
@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 (Document document : indexList) {
            System.out.println("索引列表:" + document);
        }
    }
相关推荐
Databend几秒前
Databend 产品月报(2025年6月)
数据库
Little-Hu1 小时前
QML TextEdit组件
java·服务器·数据库
保持学习ing3 小时前
day1--项目搭建and内容管理模块
java·数据库·后端·docker·虚拟机
宇钶宇夕4 小时前
EPLAN 电气制图:建立自己的部件库,添加部件-加SQL Server安装教程(三)上
运维·服务器·数据库·程序人生·自动化
爱可生开源社区4 小时前
SQLShift 重磅更新:支持 SQL Server 存储过程转换至 GaussDB!
数据库
贾修行4 小时前
SQL Server 空间函数从入门到精通:原理、实战与多数据库性能对比
数据库·sqlserver
傲祥Ax5 小时前
Redis总结
数据库·redis·redis重点总结
一屉大大大花卷5 小时前
初识Neo4j之入门介绍(一)
数据库·neo4j
周胡杰6 小时前
鸿蒙arkts使用关系型数据库,使用DB Browser for SQLite连接和查看数据库数据?使用TaskPool进行频繁数据库操作
前端·数据库·华为·harmonyos·鸿蒙·鸿蒙系统
wkj0016 小时前
navicate如何设置数据库引擎
数据库·mysql