SpringBoot将MongoDB聚合语句转Java

SpringBoot将MongoDB聚合语句转Java,第1张

SpringBoot将MongoDB聚合语句转Java

文章目录
原MongoDB语句 :

db.batch_operation_log.aggregate([
    {
        $project: {
            "queryIndex": 1,
            "status": 1,
            AType: {
                $cond: {
                    if : {
                        $eq: ["IN_PROGRESS", "$status"]
                    },
                    then: 1,
                    else : 0
                }
            },
            BType: {
                $cond: {
                    if : {
                        $eq: ["FAIL", "$status"]
                    },
                    then: 1,
                    else : 0
                }
            }
        }
    },
    {
        $group: {
            _id: {
                "status": "$status",
                "queryIndex": "$queryIndex"
            },
            queryIndex: {
                "$first": "$queryIndex"
            },
            IN_PROGRESS: {
                $sum: "$AType"
            },
            FAIL: {
                $sum: "$BType"
            }
        }
    },
    {
        $group: {
            _id: {
                "queryIndex": "$queryIndex"
            },
            queryIndex: {
                "$first": "$queryIndex"
            },
            inprogress: {
                $sum: "$IN_PROGRESS"
            },
            fail: {
                $sum: "$FAIL"
            }
        }
    }
])

SpringBoot API 转换 :

//通过任务id和阶段id进行分组 ,获取成功数和失败数
        List operations = new ArrayList<>();
        //匹配
        //operations.add(Aggregation.match(Criteria.
               //where("queryIndex").in(queryIndex)));
        //列投影
        operations.add(Aggregation.project("queryIndex", "status")
                .andexpression("{$cond: { if : { $eq: {'IN_PROGRESS', '$status'}},then:1,else:0}}").as("AType")
                .andexpression("{$cond: { if : { $eq: {'FAIL', '$status'}},then:1,else:0}}").as("BType"));
        //分组
        operations.add(Aggregation.group("status", "queryIndex")
                .sum("AType").as("IN_PROGRESS")
                .sum("BType").as("FAIL")
                .first("queryIndex").as("queryIndex"));
        //继续分组
        operations.add(Aggregation.group("queryIndex")
                .sum("IN_PROGRESS").as("inProgress")
                .sum("FAIL").as("fail")
                .first("queryIndex").as("queryIndex"));
        AggregationResults results = mongoTemplate.aggregate(Aggregation.newAggregation(
                operations.toArray(new AggregationOperation[0])
        ), "batch_operation_log", QueryCountDO.class);

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5685305.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存