@Autowired
private MongoTemplate mongoTemplate;
public String test(String bizName,String startTime,String endTime){
//查询格式 2024-04-25
String subStrExpress = "substr(createTime, 0, 10)";
Criteria criteria = new Criteria();
if (null != startTime) {
try {
criteria=Criteria.where("createTime")
.gte(DateUtils.parseDate(startTime,"yyyy-MM-dd HH:mm:ss"))
.lte(DateUtils.parseDate(endTime,"yyyy-MM-dd HH:mm:ss"));
} catch (ParseException e) {
return MsgUtil.fail();
}
}
if (StringUtils.isNotBlank(bizName)) {
criteria.and("bizName").regex(bizName);
}
Aggregation aggregation = Aggregation.newAggregation(
Aggregation.match(criteria),//查询条件,可增加多个
//存储时间格式为date类型,mongoFormat为时间格式 %Y-%m
// Aggregation.project("createTime").
// and(DateOperators.DateToString.dateOf("createTime")
// .toString("%Y-%m")).as("date"),
//存储时间格式为string类型
Aggregation.project().andExpression(subStrExpress).as("date"),
Aggregation.group("date"),
//格式化输出为:date
Aggregation.project("date").and("date").previousOperation(),
//排序
Aggregation.sort(Sort.Direction.ASC, "date")
);
AggregationResults<Document> result = mongoTemplate.aggregate(aggregation,
MogoDBContentDao.TABLE_NAME, Document.class);
List<Document> documents = result.getMappedResults();
}
Mongodb根据指定格式进行分组查询
该篇文章讲述了在SpringBoot项目中,如何使用@Autowired注入MongoTemplate进行数据库查询,特别是针对特定业务名称(bizName)和时间范围(startTime,endTime),并利用Aggregation进行数据处理,包括日期格式转换和排序的过程。
摘要由CSDN通过智能技术生成