java操作mongo,按格式化时间分组

呕心沥血,终于让我这个mongo小白成功解决了问题!

•$project -  可以重构数据
•$match - 可以实现类似query的功能
•$limit - 限制返回个数
•$group - 统计操作, 还提供了一系列子命令
•$sort  - 排序

直接上代码:

Criteria criteriaTwo = Criteria.where("isDelete").is(0).and("isAble").is(1);
Aggregation agg = Aggregation.newAggregation(
      match(criteriaTwo),
      Aggregation.project("releaseTime").andExpression("releaseTime").substring(0,10).as("times"),
      Aggregation.group("times").count().as("count"));
AggregationResults<Map> aMap = mongoTemplateApi.aggregate(agg,AInfo.class,Map.class);

如果为数据库字段为时间类型

Aggregation.project("isTure").and(DateOperators.DateToString.dateOf( "orderTime" ).toString("%Y -%m-%d")).as("times")

成功解决,完美!
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
MongoDB中,时间数据存储为ISODate对象。在Spring Data MongoDB中,可以使用MongoTemplate来查询和操作MongoDB数据库。 要查询时间并将其格式化,可以使用Java中的SimpleDateFormat类。以下是一个示例代码,可以查询MongoDB中的时间字段,并将其格式化为指定的日期格式: ```java import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.TimeZone; public class Example { private MongoTemplate mongoTemplate; public Example(MongoTemplate mongoTemplate) { this.mongoTemplate = mongoTemplate; } public void queryAndFormatDate() { // 查询条件 Query query = new Query(Criteria.where("create_time").gte(new Date(1626940800000L))); // 查询2021-07-22之后的数据 // 查询结果 List<YourEntity> result = mongoTemplate.find(query, YourEntity.class); // 格式化时间 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai")); // 输出结果 for (YourEntity entity : result) { Date date = entity.getCreateTime(); String formattedDate = dateFormat.format(date); System.out.println(formattedDate); } } } ``` 上面的示例代码中,我们首先使用MongoTemplate查询MongoDB中的数据。查询条件是文档中的`create_time`字段大于等于指定的日期。然后,我们获取查询结果,并使用SimpleDateFormat类将时间格式为指定的日期格式。最后,我们输出格式化后的时间字符串。 需要注意的是,MongoDB中存储的时间是UTC时间,如果要将其转换为本地时间,需要使用TimeZone类设置时区。在上面的示例代码中,我们将时区设置为“Asia/Shanghai”。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值