Java中简单使用MongoTemplate 操作MongoDB

Java中简单使用MongoTemplate 操作MongoDB

前提:SpringBoot项目

添加依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-data-mongodbartifactId>
    dependency>
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-webartifactId>
    dependency>

    <dependency>
        <groupId>org.projectlombokgroupId>
        <artifactId>lombokartifactId>
    dependency>

    <dependency>
        <groupId>joda-timegroupId>
        <artifactId>joda-timeartifactId>
        <version>2.10.1version>
    dependency>

    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-testartifactId>
        <scope>testscope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintagegroupId>
                <artifactId>junit-vintage-engineartifactId>
            exclusion>
        exclusions>
    dependency>
dependencies>

applicatin.properties

spring.data.mongodb.uri=mongodb://192.168.109.139:27017/test
# mongodb://你的主机:你的mongo端口/对应Mongo数据库

实体类

@Data
@Document("User") // 对应数据库表
public class User {
    @Id	
    private String id;	// _id字段 由Mongo自动生成
    private String name;
    private Integer age;
    private String email;
    private String createDate;
}

直接注入即可

@Autowired
private MongoTemplate mongoTemplate;

添加操作

@Test
public void add() {
    User user = new User();
    user.setAge(19);
    user.setName("李华");
    user.setEmail("[email protected]");
    User user1 = mongoTemplate.insert(user);
    System.out.println(user1);
}

查询所有

@Test
void findAll() {
    List<User> userList = mongoTemplate.findAll(User.class);
    System.out.println(userList);
}

根据id查询

@Test
void findById() {
    String id = "604dbbd87010e778b026ebe2";
    User user = mongoTemplate.findById(id, User.class);
    System.out.println(user);
}

条件查询

@Test
void find() {
    
    // 相当于select * from user where name = '王五' and age = 19
    Query query = new Query(
        Criteria.where("name").is("王五")
        .and("age").is(19));
    List<User> userList = mongoTemplate.find(query, User.class);
    System.out.println(userList);
}

模糊查询(使用正则匹配)

@Test
void findLike() {
    String name = "李";
    String regex = String.format("%s%s%s","^.*" , name , ".$");
    // 定义正则表达式 Pattern.CASE_INSENSITIVE 忽略大小写
    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);
}

分页查询

@Test
void findPage() {
    Integer pageNum = 1;
    Integer pageSize = 3;

    String name = "李";
    String regex = String.format("%s%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);
    
    // skip跳过多少个,limit 需要查询多少
    List<User> userList = mongoTemplate.find(
        query.skip((pageNum - 1) * pageSize).limit(pageSize), User.class);

    System.out.println(count);
    System.out.println(userList);
}

修改

@Test
void update() {
    User user = mongoTemplate.findById("604dbbd87010e778b026ebe2", User.class);
    user.setName("lisi");
    user.setAge(23);
    // 定义where 条件
    Query query = new Query(Criteria.where("_id").is("604dbbd87010e778b026ebe2"));
    
    // 定义修改信息
    Update update = new Update()
        .set("name",user.getName()).set("age",user.getAge());
    UpdateResult updateResult = mongoTemplate.upsert(query, update, User.class);
    System.out.println(updateResult.getModifiedCount());
}

删除

@Test
void delete() {
    Query query = new Query(Criteria.where("name").is("李华"));
    DeleteResult deleteResult = mongoTemplate.remove(query, User.class);
    System.out.println(deleteResult.getDeletedCount());
}

你可能感兴趣的:(mongodb,mongodb,数据库)