解决方案:给 $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}}
]);



