Java中使用MongoTemplate 简单操作MongoDB

@Autowired
private MongoTemplate mongoTemplate;
 

User:封装的对象

插入:mongoTemplate.insert(user);

根据id查询:mongoTemplate.findById(id, User.class);

查询所有:mongoTemplate.findAll(User.class);

条件查询:

Query query = new Query(
        Criteria.where("name").is("迪丽热巴")
        .and("age").is(25));
    List userList = mongoTemplate.find(query, User.class);


模糊查询:

 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 userList = mongoTemplate.find(query, User.class);

分页查询:

  Integer pageNum = 1;
  Integer pageSize = 3;
// skip跳过多少个,limit 需要查询多少
    List userList = mongoTemplate.find(
        query.skip((pageNum - 1) * pageSize).limit(pageSize), User.class);

修改:

@Test
void update() {
    User user = mongoTemplate.findById("456189465144321854", User.class);
    user.setName("张三");
    user.setAge(21);

    // where
    Query query = new Query(Criteria.where("_id").is("456189465144321854"));
    
    // 修改信息
    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,数据库)