如何使用MongoTemplate执行各种增删改查的语句
1.案例代码如:
Query query=new Query(Criteria.where("userName").is(userName)); UserEntity user = mongoTemplate.findOne(query , UserEntity.class);
2.各种增删改如下;
增
mongoTemplate.save(user);
删
mongoTemplate.remove(query,UserEntity.class);
改
Update update= new Update().set("userName", user.getUserName()).set("passWord", user.getPassWord());
//更新查询返回结果集的第一条
WriteResult result =mongoTemplate.updateFirst(query,update,UserEntity.class);
查
Query query=new Query(Criteria.where("userName").is(userName));
UserEntity user = mongoTemplate.findOne(query , UserEntity.class);
3.MongoDB分页查询如下所示:
//利用工具类拼装分页信息
SpringbootMongoDBPageable pageable = new SpringbootMongoDBPageable();
MongoDBPageModel pm=new MongoDBPageModel();
pm.setPagesize(3);
pm.setPagenumber(1);
List<Order> orders = new ArrayList<>();
//排序信息
orders.add(new Order(Direction.DESC, "age"));
Sort sort = new Sort(orders);
pm.setSort(sort);
pageable.setPage(pm);
//拼装查询信息
Query query = new Query();
Criteria criteria = new Criteria();
query.addCriteria(criteria.where("age").gte(6).lte(18));
//检索6-18岁的
query.addCriteria(criteria.where("name").regex("文"));
//模糊查询名字
Long count = mongoTemplate.count(query, OrdersData.class);
//查询总记录数
List<Entry> list = mongoTemplate.find(query.with(pageable), Entry.class);