1.pom.xml引入Jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
2.MongoDbHelper封装
/**
* MongoDB Operation class
* @author HyoJung
* @date 2024-03-05
*/
public class MongoDbHelper {
@Autowired
private MongoTemplate mongoTemplate;
/**
* Save Individual Objects
*
* @param t 实体类参数
* @param <T> 实体类
* @return
*/
public <T> T save(T t) {
return mongoTemplate.insert(t);
}
/**
* Store the object to the specified collectionName
* @param objectToSave
* @param collectionName 类似SQL数据库的表名
* @param <T>
* @return
*/
public <T> T save(T objectToSave, String collectionName){
return mongoTemplate.insert(objectToSave,collectionName);
}
/**
* 批量存储
*
* @param list
* @param collectionName
* @return
*/
public <T> Collection<T> batchSave(Collection<T> list, String collectionName) {
return mongoTemplate.insert(list,collectionName);
}
/**
* Query Data
*
* @param query
* @param tClass
* @param <T>
* @return
*/
public <T> List<T> find(Query query, Class<T> tClass) {
return mongoTemplate.find(query, tClass);
}
/**
* Collection specified by query data
*
* @param query
* @param tClass
* @param <T>
* @return
*/
public <T> List<T> find(Query query, Class<T> tClass, String collectionName) {
return mongoTemplate.find(query, tClass,collectionName);
}
/**
* 分页查询
* @param query query criteria
* @param pageNum Current Page
* @param pageSize Number of entries per page
* @param sortField Sorted Field
* @param sortType 1:asc;0:desc
* @param tClass to class
* @param collectionName collection name
* @param <T>
* @return
*/
public <T> MongoPage findByPage(Query query,int pageNum,int pageSize,String sortField,int sortType, Class<T> tClass, String collectionName) {
int count = (int) mongoTemplate.count(query, tClass, collectionName);
if(sortType==1){
query.with(Sort.by(Sort.Order.asc(sortField)));
}else {
query.with(Sort.by(Sort.Order.desc(sortField)));
}
//Set starting number
query.skip((pageNum - 1) * pageSize);
//Set the number of queries
query.limit(pageSize);
//Query the current page data set
List<T> taskList = mongoTemplate.find(query, tClass,collectionName);
int size=count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
MongoPage page=new MongoPage();
page.setTotal(count);
page.setSize(size);
page.setData(taskList);
return page;
}
/**
* 查询前几条数据
* @param query
* @param limitNum 前几条
* @param sortField 排序字段
* @param sortType 0:倒序;1:正序
* @param tClass
* @param collectionName
* @param <T>
* @return
*/
public <T> List<T> findTop(Query query,Integer limitNum,String sortField,int sortType, Class<T> tClass, String collectionName){
if(sortType==1){
query.with(Sort.by(Sort.Order.asc(sortField)));
}else {
query.with(Sort.by(Sort.Order.desc(sortField)));
}
query.limit(limitNum);
return mongoTemplate.find(query, tClass,collectionName);
}
/**
* 查询一条数据
* @param query
* @param sortField
*