Mongodb根据指定格式进行分组查询

该篇文章讲述了在SpringBoot项目中,如何使用@Autowired注入MongoTemplate进行数据库查询,特别是针对特定业务名称(bizName)和时间范围(startTime,endTime),并利用Aggregation进行数据处理,包括日期格式转换和排序的过程。
摘要由CSDN通过智能技术生成
    @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();
		
	}

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值