【问题标题】:Aggregation.group("").sum("") How to write the calculation formula?Aggregation.group("").sum("") 计算公式怎么写?
【发布时间】:2023-03-07 22:53:01
【问题描述】:

这是 Mongo 脚本

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

这是Java代码

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

脚本可以写在“sum()”函数中吗?我该怎么写?

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework aggregate mongotemplate


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-02
      相关资源
      最近更新 更多