1.添加maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
2.接口继承mongo的api仓库(MongoRepository)进行增删改查,和springDataJpa差不多
public interface StudentRepository extends MongoRepository<Student, ObjectId>
{
}
3.分页,模糊查询,时间查询
int pageNum = studentRequest.getPageNum();
int pageSize = studentRequest.getPageSize();
if (pageNum <= 0)
{
pageNum = 1;
}
pageNum = pageNum - 1;
if (pageSize <= 0)
{
pageSize = 10;
}
Student student = new Student ();
BeanUtils.copyProperties(studentRequest, student );
//创建匹配器
ExampleMatcher matcher = ExampleMatcher.matching()
.withMatcher("name", match -> match.contains().ignoreCase()) //根据名字模糊匹配
.withMatcher("age", match -> match.exact()) //根据年龄精确查询
.withIgnorePaths("pageNum", "pageSize", "Id", "address");//忽略基本类型
//创建实例
Example<Student > example = Example.of(Student , matcher);
Query query = new Query(Criteria.byExample(example));
if (studentRequest.getStartTime() != null && studentRequest.getEndTime() != null){
query.addCriteria(Criteria.where("datetime")
.gte(studentRequest.getStartTime())
.lte(studentRequest.getEndTime()));
}
else
{
if (studentRequest.getStartTime() != null)
{
query.addCriteria(Criteria.where("datetime").gte(studentRequest.getStartTime()));
}
if (studentRequest.getEndTime() != null)
{
query.addCriteria(Criteria.where("datetime").lte(studentRequest.getEndTime()));
}
}
Pageable pageable = PageRequest.of(pageNum, pageSize, Sort.Direction.DESC, "datetime"); //根据创建的时间降序
//计算总数
long total = mongoTemplate.count(query, Student .class);
// Page<Student> page = studentRepository.findAll(example, pageable);
//查询结果集
List<Student> studentList= mongoTemplate.find(query.with(pageable), Student.class);
Page<Student> page = new PageImpl(studentList, pageable, total);
QueryResult queryResult = new QueryResult();
queryResult.setTotalPage(page.getTotalPages());
queryResult.setTotalCount(page.getTotalElements());
queryResult.setList(page.getContent());
return R.ok().put("data", queryResult);