MongoDB聚合语句转成SpringBoot API

文章目录


原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<AggregationOperation> 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<QueryCountDO> results = mongoTemplate.aggregate(Aggregation.newAggregation(
                operations.toArray(new AggregationOperation[0])
        ), "batch_operation_log", QueryCountDO.class);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值