@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<User> 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<User> userList = mongoTemplate.find(query, User.class);
分页查询:
Integer pageNum = 1;
Integer pageSize = 3;
// skip跳过多少个,limit 需要查询多少
List<User> userList = mongoTemplate.find(
query.skip((pageNum - 1) * pageSize).limit(pageSize), User.class);
修改:文章来源:https://www.toymoban.com/news/detail-673824.html
@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());
}
删除:文章来源地址https://www.toymoban.com/news/detail-673824.html
@Test
void delete() {
Query query = new Query(Criteria.where("name").is("张三"));
DeleteResult deleteResult = mongoTemplate.remove(query, User.class);
System.out.println(deleteResult.getDeletedCount());
}
到了这里,关于Java中使用MongoTemplate 简单操作MongoDB的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!