在 MongoDB/Spring 中包含多个条件

Concat with multiple conditions in MongoDB/Spring

我正在尝试实施 MongoDB 查询以对范围内的数据进行分组和计数。我从 Lee Sherwood 那里找到了精彩的 post 解释了如何实现这一点并将其重新用于我的数据库。问题是我正在使用 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部分怎么写?

您可以使用 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());