栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

MongoDB 统计月份多了个月的 Bug 解决

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

MongoDB 统计月份多了个月的 Bug 解决

解决方案:给 $dateToString 加时区

Java:

 Criteria criteria = this.statsCriteria(request);
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.project()
                        .and("payMoney").as("pay_money")              // 要用 Java 字段转下
                        .and(DateOperators.DateToString.dateOf("billingDate")
                                .toString("%Y-%m")
                                .withTimezone(DateOperators.Timezone.valueOf("+08:00"))) // 要设置时区
                        .as("month"),
                Aggregation.group("$month")
                        .sum(ConvertOperators.ToDecimal.toDecimal("$pay_money")) // 用 $ 和下划线
                        .as("sum_money"),                                   // 要用下划线
                Aggregation.sort(Sort.by(Sort.Direction.DESC, "_id"))
        );
        log.info("agg: [{}]", agg);

 agg 输出内容:

[
  {
    "aggregate": "__collection__",
    "pipeline": [
      {
        "$match": {
          "$and": [
            {
              "billing_date": {
                "$gte": {
                  "$java": "2022-01-01"
                }
              }
            },
            {
              "billing_date": {
                "$lte": {
                  "$java": "2022-02-28"
                }
              }
            }
          ]
        }
      },
      {
        "$project": {
          "pay_money": "$payMoney",
          "month": {
            "$dateToString": {
              "format": "%Y-%m",
              "date": "$billingDate",
              "timezone": "+08:00"
            }
          }
        }
      },
      {
        "$group": {
          "_id": "$month",
          "sum_money": {
            "$sum": {
              "$toDecimal": "$pay_money"
            }
          }
        }
      },
      {
        "$sort": {
          "_id": -1
        }
      }
    ]
  }
]

JS:

db.t_instance_order.aggregate([
    {$match: {billing_date: {$gte: ISODate("2021-12-31T16:00:00.000Z"), $lte: ISODate("2022-02-27T16:00:00.000Z")}}},
    {$project: {pay_money: 1, month: {$dateToString: {date: "$billing_date", format: "%Y-%m", timezone: "+08:00"}}}},
    {$group: {_id: "$month", sum_money: {$sum: {$toDecimal: "$pay_money"}}}},
    {$sort: {_id: -1}}
]);

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/777397.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号