集成简介

spring-data-mongodb提供了MongoTemplateMongoRepository两种方式访问mongodb,MongoRepository操作简单,MongoTemplate操作灵活,我们在项目中可以灵活适用这两种方式操作mongodb,MongoRepository的缺点是不够灵活,MongoTemplate正好可以弥补不足。

搭建开发环境

1、创建springboot项目

2、导入依赖


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

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>

    <dependency>
        <groupId>joda-time</groupId>
        <artifactId>joda-time</artifactId>
        <version>2.10.1</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

3 添加application配置


spring.data.mongodb.uri=mongodb://192.168.217.128:27017/test

4.添加实体


@Data
@Document("User")
public class User {

 @Id
 private String id;
 private String name;
 private Integer age;
 private String email;
 private String createDate;
}

添加操作


package com.study;

import com.study.mongodb.entiity.User;
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 SpringbootMongoDbApplicationTests {

    //注入mongoTemplate
    @Autowired
    private MongoTemplate mongoTemplate;

    //添加操作
    @Test
    void create() {
        User user = new User();
        user.setAge(20);
        user.setName("zhangsan");
        user.setEmail("111112222333@qq.com")
        User insert = mongoTemplate.insert(user);
        System.out.println(insert);
    }
}


MongoTemplate操作MongoDB_List

查询操作

1.查询所有


//查询所有
@Test
public void findAll(){
    List<User> userList = mongoTemplate.findAll(User.class);
    System.out.println(userList);
}


MongoTemplate操作MongoDB_spring_02

2.根据id查询


//根据id查询
@Test
public void findId(){
    User user = mongoTemplate.findById("611a1cf8d5ba747098ff4625", User.class);
    System.out.println(user);
}


MongoTemplate操作MongoDB_spring_03

3.条件查询


//条件查询
@Test
public void findUserList(){
    //name = zhangsan and age =20
    Query query = new Query(Criteria.where("name").is("zhangsan").and("age").is(20));
    List<User> userList = mongoTemplate.find(query, User.class);
    System.out.println(userList);
}


MongoTemplate操作MongoDB_spring_04

4.模糊查询


//模糊查询
    @Test
    public void findLikeUserList(){
        //name like zhangsan
        //regex(Pattern)正则表达式
        String name = "hangsan";
        String regex = String.format("%s%s","^.*",name);
        Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        Query query = new Query(Criteria.where("name").regex(pattern));
        List<User> userList = mongoTemplate.find(query, User.class);
        System.out.println(userList);
    }


MongoTemplate操作MongoDB_List_05

5.分页查询


//分页查询
    @Test
    public void findPageUserList(){
        int pageNo = 1;
        int pageSize = 3;
        //条件构建
        String name = "hangsan";
        String regex = String.format("%s%s","^.*",name);
        Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        Query query = new Query(Criteria.where("name").regex(pattern));
        //分页构建
        //查询记录数
        long count = mongoTemplate.count(query, User.class);
        //分页
        List<User> userList = mongoTemplate.find(query.skip((pageNo - 1) * pageSize).limit(pageSize), User.class);
        System.out.println(count);
        System.out.println(userList);
    }


MongoTemplate操作MongoDB_List_06

修改操作


//修改
    @Test
    public void updateUser(){
        //根据id查询数据
        User user = mongoTemplate.findById("611a1cf8d5ba747098ff4625", User.class);
        //设置修改的值
        user.setName("lisi");
        user.setAge(18);
        //调用方法实现修改操作
        Query query = new Query(Criteria.where("_id").is(user.getId()));
        Update update = new Update();
        update.set("name",user.getName());
        update.set("age",user.getAge());
        UpdateResult upsert = mongoTemplate.upsert(query, update, User.class);
        long count = upsert.getModifiedCount();
        System.out.println(count);
    }


MongoTemplate操作MongoDB_List_07


MongoTemplate操作MongoDB_spring_08

删除操作


//删除操作
    @Test
    public void deleteUser(){
        Query query = new Query(Criteria.where("_id").is("611a1cf8d5ba747098ff4625"));
        DeleteResult remove = mongoTemplate.remove(query, User.class);
        long deletedCount = remove.getDeletedCount();
        System.out.println(deletedCount);
    }


MongoTemplate操作MongoDB_spring_09


MongoTemplate操作MongoDB_User_10