在MongoDB / Spring中具有多个条件的Concat

问题描述 投票:2回答:1

我正在尝试实现一个MongoDB查询来对范围内的数据进行分组和计数。我找到了Lee Sherwood的精彩帖子,解释了如何实现这一点,并将其重新用于我的数据库。问题是我正在使用Spring,我需要使用Java编写它。我设法正确地写了聚合的两个部分,但我坚持这个:

$project: {
    "range": {
        $concat: [
            { $cond: [{ $and:[ {$gt:["$dose", 0 ]}, {$lt: ["$dose", 50]}]}, "0-50", ""] },
            { $cond: [{ $and:[ {$gt:["$dose", 50 ]}, {$lt: ["$dose", 100]}]}, "50-100", ""] },
            { $cond: [{ $and:[ {$gt:["$dose", 100 ]}, {$lt: ["$dose", 150]}]}, "100-150", ""] },
            { $cond: [{ $and:[ {$gt:["$dose", 150 ]}, {$lt: ["$dose", 200]}]}, "150-200", ""] },
            { $cond: [{ $and:[ {$gt:["$dose", 200 ]}, {$lt: ["$dose", 250]}]}, "200-250", ""] },
            { $cond: [{ $and:[ {$gt:["$dose", 250 ]}, {$lt: ["$dose", 300]}]}, "250-300", ""] },
            { $cond: [{ $gte:["$dose", 300] }, "300+", ""]}
        ]
    }
}

这是我现在的代码:

    ProjectionOperation.ProjectionOperationBuilder projectBuilder = Aggregation.project().and("dose");
    for (int startRange = 0; startRange <= 350; startRange += step) {
        int endRange = startRange + step;
        projectBuilder.concat(...)
    }
    return projectBuilder.as("range");

你怎么写包含所有条件的concat部分?

spring mongodb spring-data-mongodb
1个回答
0
投票

您可以使用switch语句和条件来完成此操作。我写了一个例子,下面是1个案例。根据需要添加尽可能多的案例以满足您的范围要求。

List<AggregationOperation> operationList = new ArrayList<>();
List<ConditionalOperators.Switch.CaseOperator> cases = new ArrayList<>();
ConditionalOperators.Switch.CaseOperator cond1 = ConditionalOperators.Switch.CaseOperator.when(BooleanOperators.And.and(ComparisonOperators.valueOf("dose").greaterThanValue(0), ComparisonOperators.valueOf("dose").lessThanValue(50)))
                .then("0-50");
cases.add(cond1);

ProjectionOperation projectionOperation = Aggregation.project().and(ConditionalOperators.switchCases(cases)).as("range");
operationList.add(projectionOperation);

System.out.println(aggregation.toString());
© www.soinside.com 2019 - 2024. All rights reserved.