@SpringBootTest
class SpringbootMongodbApplicationTests {
@Autowired
private MongoTemplate mongoTemplate;
@Test
//1. 添加数据
public void createUser(){
User user = new User();
user.setName("ljx");
user.setAge(25);
user.setEmail("ssssssssss@qq.com");
user.setCreateDate(new Date());
mongoTemplate.insert(user);
System.out.println(user);
}
@Test
//2.根据ID查询数据
public void getById(){
User user = mongoTemplate.findById("623adb2174ce277ed78cc019", User.class);
System.out.println(user);
}
@Test
//3. 查询所有数据
public void getAllUser(){
List<User> users = mongoTemplate.findAll(User.class);
for (int i = 0; i < users.size(); i++) {
System.out.println(users.get(i));
}
}
@Test
//4. 更新数据
public void updateById(){
Query query = new Query(Criteria.where("_id").is("623adb2174ce277ed78cc019"));
Update update = new Update();
update.set("age",20);
update.set("name","dfk");
UpdateResult result = mongoTemplate.upsert(query, update, User.class);
long count = result.getModifiedCount();
System.out.println(count);
}
@Test
//5. 删除数据
public void delete(){
Query query = new Query(Criteria.where("name").is("ljp"));
DeleteResult remove = mongoTemplate.remove(query, User.class);
long cnt = remove.getDeletedCount();
System.out.println(cnt);
}
@Test
//6. 条件查询
public void findUserList(){
Query query = new Query(Criteria.where("name").is("ljp")
.and("age").is(22));
List<User> users = mongoTemplate.find(query, User.class);
for (int i = 0; i < users.size(); i++) {
System.out.println(users.get(i));
}
}
@Test
//7. 模糊查询
public void findUserLikeName(){
//前三行都是为了构造pattern
String name = "j";
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));
List<User> users = mongoTemplate.find(query, User.class);
for (int i = 0; i < users.size(); i++) {
System.out.println(users.get(i));
}
}
@Test
//8.分页查询
public void findUserPage(){
int pageNo = 1;
int pageSize = 3;
String name = "j";
String regex = String.format("%s%s%s", "^.*", name, ".*$");
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Query query = new Query();
query.addCriteria(Criteria.where("name").regex(pattern));
int totalCount = (int) mongoTemplate.count(query, User.class);
List<User> users = mongoTemplate.find(query.skip((pageNo - 1) *
pageSize).limit(pageSize), User.class);
System.out.println(totalCount);
for (int i = 0; i < users.size(); i++) {
System.out.println(users.get(i));
}
}
}
MongoDB利用MongoTemplate对单表的增删改查
最新推荐文章于 2024-05-31 10:22:26 发布