Aggregation.group("").sum("") 计算公式怎么写?

Aggregation.group("").sum("") How to write the calculation formula?

This is the Mongo script

db.servicer_online_time.aggregate(
    [
        {
            $group: {
                _id : "$csId" ,
                totalTime: {
                    $sum: {
                        $multiply: ["$offlineTime", "$onlineTime"]
                    }
                }
            }
        },
    ]
);

This is Java code

GroupOperation groupOperation = Aggregation.group("csId").sum("$multiply: [\"$offlineTime\", \"$onlineTime\"]").as("");

脚本可以写在"sum()"函数里吗?我该怎么写?

您可以尝试先在投影操作中使用 SpEL andExpression 来投影字段,然后在组操作中聚合新字段:

Aggregation agg = newAggregation(
    project("csId").andExpression("offlineTime * onlineTime").as("timesProduct"),
    group("csId").sum("timesProduct").as("totalTime")
);