/**
* mongo 分页
*/
@Test
public void testPage() {
int pageSize = 10;
int currentNo = 0;
Query query = new Query();
query.addCriteria(Criteria.where("username").is("小明"));
long count = mongoTemplate.count(query, User.class);
long totalPage = count % pageSize == 0 ? count / pageSize : count / pageSize + 1L;
for (int i = 0; i < totalPage; i++) {
long skip = i * pageSize;
query.limit(pageSize);//pageSize 10 每页大小
query.skip(skip); //那哪个位置开始截取
currentNo = i + 1;
System.out.println("第:" + currentNo + "页数。。。。。");
List<User> list = mongoTemplate.find(query, User.class, "user");
for (User user : list) {
System.out.println(user.getAge() + " name:" + user.getUsername());
}
}
}
save
@Test
public void add() {
User user = new User();
user.setAge(999);
user.setUsername("刘能");
user.setCreateTime(new Date());
User result = mongoTemplate.save(user);
System.out.println(result.toString());
}
query
@Test
public void query() {
Query query = new Query();
query.addCriteria(Criteria.where("age").is(23));
query.addCriteria(Criteria.where("_id").is(new ObjectId("5e4a26b49c859929f823758d")));
List<User> list = mongoTemplate.find(query, User.class, "user");
list.forEach(x -> {
System.out.println(x.toString());
});
}
update
@Test
public void update() {
Query query = new Query();
query.addCriteria(Criteria.where("age").is(23));
query.addCriteria(Criteria.where("_id").is(new ObjectId("5e4a2952c129812641d97ea9")));
Update update = new Update();
update.set("username", "赵四");
UpdateResult result = mongoTemplate.updateFirst(query, update, "user");
System.out.println(result.toString());
}
delete
@Testpublic void delete() {
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(new ObjectId("5e4a299808cfaa306692910c")));
DeleteResult result = mongoTemplate.remove(query, "user");
System.out.println(result);
}