首页 > 解决方案 > 在 Spring Mongo 中进行聚合时为 ConditionalOperators 传递动态值

问题描述

我是 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;

我已经硬编码了临时值。

标签: javaspringmongodbaggregation-framework

解决方案


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

 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;
}

推荐阅读