java - 在 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;
我已经硬编码了临时值。
解决方案
我想出了一种动态添加条件的方法,而无需使用以下代码片段对值进行硬编码。发布它,以便对其他人有用。让我知道是否有更好的方法来做到这一点。
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;
}
推荐阅读
- python-3.x - kivy 应用程序适用于计算机,但不适用于移动设备
- nodatime - 尝试将 Microsoft Windows BCL 区域映射到 Tzdb 区域以访问其缩写值
- javascript - 如何从 Nuxt.js SPA 运行 Python 脚本?
- angular - 从子出口角度导航到根?
- javascript - vue v-if="isEditable" @click.prevent
- c# - 从用户控件访问主窗口
- sql-server - 在eclipse上的maven web项目中连接JDBC
- android - 不要在单击上居中标记
- javascript - 如何手动取消选中/选中primeng复选框
- python - 为什么是
.format 在我继承的类对象中给了我这个奇怪的输出?(蟒蛇新手)