mongoDB-使用$substr

需求说明

现在需要根据订单支付时间计算近几天的支付订单数,根据支付时间日期作为分组.现有的订单数据结构如下:


mongoDB-使用$substr_第1张图片
订单数据结构

问题

因为保存的支付时间格式为yyyy-MM-dd HH:mm:ss,显然我们分组时无法按照日分组,所以需要裁剪支付时间.查找官方文档,语法如下:{ $substr: [ , , ] }.官方链接如下:$substr

查询语法:

db.order_order.aggregate([
{$match:{"payment_time":{$gte:"2020-05-20",$lt:"2020-05-28"}}},//根据时间筛选
{$project:{"date_str":{$substr:["$payment_time",0,10]}}},//裁剪生成新字段
{$group:{_id:"$date_str","count":{$sum:1}}},//根据日期分组
{$sort:{"_id":1}}//排序
])

使用springdata转化成java代码如下:

        MatchOperation match = Aggregation.match(Criteria.where("payment_time").gte(startDate).lt(endDate));
        StringOperators.Substr substr = StringOperators.Substr.valueOf("$payment_time").substring(0, 10);
        ProjectionOperation project = Aggregation.project().and(substr).as("date_str");
        GroupOperation group = Aggregation.group("$date_str").count().as("count");
        SortOperation sort = Aggregation.sort(Sort.by("_id").ascending());
        Aggregation agg = Aggregation.newAggregation(match, project, group, sort);

最后结果如下:

{ "_id" : "2020-05-20", "count" : 3710 }
{ "_id" : "2020-05-21", "count" : 3257 }
{ "_id" : "2020-05-22", "count" : 2466 }
{ "_id" : "2020-05-23", "count" : 2088 }
{ "_id" : "2020-05-24", "count" : 2430 }
{ "_id" : "2020-05-25", "count" : 7531 }
{ "_id" : "2020-05-26", "count" : 2593 }
{ "_id" : "2020-05-27", "count" : 2297 }

后记

之前有人问我怎么找到这些内容的,我大概说一下怎么找到的吧。第一步去官网文档找到对应的api的写法,然后写出来进行查询验证。第二步转化成java代码,我也没有看完所有的源码,但是用好全局搜索,通过全局搜索能找到对应的java类。例如我刚一开始也不知道$sbustr怎样转化成java代码,但是我通过全局搜索$substr找到了相关的类。对于其他语言应该同样适用。以后是别的api我同样也能通过这种方式找到。

你可能感兴趣的:(mongoDB-使用$substr)