【问题标题】:Passing dynamic values for ConditionalOperators when Aggregating in Spring Mongo在 Spring Mongo 中进行聚合时为 ConditionalOperators 传递动态值
【发布时间】:2020-09-09 01:10:39
【问题描述】:

我是 mongo 聚合的新手,我想检查在 spring mongo 中是否可以进行以下操作。我知道我们可以写出给定的条件,

ConditionalOperators.Cond cond = when(Criteria.where("status").is("PRESENT")).then(1)
                .otherwise(when(Criteria.where("status").is("ABSENT")).then(2)
                .otherwise(100)); 

鉴于我有可能的条件值的映射,我想知道是否可以使用映射将值传递给条件。

Map<String, Integer> dynamicValues = new HashMap<>();
dynamicValues.put("PRESENT", 1);
dynamicValues.put("ABSENT", 2);

这就是我现在所拥有的。但它没有按预期工作。

List<String> dynamicValues = Arrays.asList("PRESENT", "ABSENT");

ConditionalOperators.Cond.OtherwiseBuilder operator =  ConditionalOperators.when(Criteria.where("status").is(dynamicValues.get(0))).then(0));

        for (String s : dynamicValues) {
            ConditionalOperators.Cond.OtherwiseBuilder shippingDestination = when(Criteria.where("status").is(s)).then(1);
            operator.otherwise(shippingDestination);
        }

        return (ConditionalOperators.Cond) operator;

我已经硬编码了 then 临时值。

【问题讨论】:

  • 能否提供完整的查询?
  • @Valijon,我已经在代码中添加了当前的实现。但不幸的是,它不起作用。

标签: java spring mongodb aggregation-framework


【解决方案1】:

我想出了一种方法来动态添加条件,而无需使用以下代码 sn-p 对值进行硬编码。发布它,以便对其他人有用。让我知道是否有更好的方法来做到这一点。

 private ConditionalOperators.Cond buildCondition() {
    List<String> elements = Arrays.asList("ABSENT", "PRESENT");
    ConditionalOperators.Cond previousCondition = null;
    ConditionalOperators.Cond resultCondition = null;

    //#### Conditions cannot be built without the otherwise condition, therefore, build conditions in reverse.
    ListIterator<String> listIterator = elements.listIterator(elements.size());

    while (listIterator.hasPrevious()) {
        ConditionalOperators.Cond currentCondition;
        boolean isLastElement = !listIterator.hasNext();
        String currentElement = listIterator.previous();
        // create the otherwise condition with the dynamic destination and priority.
        ConditionalOperators.Cond.OtherwiseBuilder otherWiseCondition = when(Criteria.where("status")
                .is(currentElement))
                .then(<add the real value>);

        if (isLastElement) {
            // if last element, add the else condition.
            currentCondition = otherWiseCondition.otherwise(<else condition value>);
        } else {
            //add the previous element as the otherwise condition.
            currentCondition = otherWiseCondition.otherwise(previousCondition);
        }

        resultCondition = currentCondition;
        previousCondition = currentCondition;
    }

    return resultCondition;
}

【讨论】:

    猜你喜欢
    • 2018-09-25
    • 2019-10-14
    • 2020-04-29
    • 1970-01-01
    • 1970-01-01
    • 2021-11-23
    • 1970-01-01
    • 2018-01-12
    • 2016-11-08
    相关资源
    最近更新 更多