Spring Data 中的 MongoDB $addField 和 $indexOfArray [英] MongoDB $addField and $indexOfArray in Spring Data
问题描述
我正在尝试根据 Asya Kamsky 的 post:
I am trying to implement a custom sort with MongoDB and Spring Data according to Asya Kamsky's post:
List<AggregationOperation> operations = new ArrayList<>();
operations.add(Aggregation.addFields().addField("scorrrz")
.withValueOfExpression("{ \"$indexOfArray\" : [ [\"John\", \"Bill\"], \"$name\" ] }").build());
当我尝试执行此操作时,我得到:
When I try to execute this, I get:
ERROR a.insurance.misc.ErrorAttributes - /api/v1/insurance/opportunity/all
org.springframework.expression.spel.SpelParseException: Expression [{ "$indexOfArray" : [ ["John", "Bill"], "$name" ] }] @29: EL1043E: Unexpected token. Expected 'rsquare(])' but was 'comma(,)'
这不是正确的语法吗?如何使用 Spring Data 做到这一点?
Is this not the right syntaxt? How can this be done with Spring Data?
推荐答案
Collection<String> nameList = Arrays.asList("John", "Bill");
Aggregation agg = newAggregation(
addFields()
.addField("scorrrz").withValue(arrayOf(nameList).indexOf("$name"))
.build()
);
聚合的投影是一个带有 $indexOfArray
聚合数组操作的 $addFields
阶段.这将返回一个字段scorrrz
,当没有匹配时,它将具有索引值或-1
.这在 Spring Boot v2.3.10 和 MongoDB v4.2.8 上运行良好.
The aggregation's projection is an $addFields
stage with a $indexOfArray
aggregation array operation. This will return a field scorrrz
, and it will have index value or -1
when there is no match. This ran okay with Spring Boot v2.3.10 and MongoDB v4.2.8.
运行此聚合将管道 agg
传递给 MongoTemplate#aggregate
方法.
The run this aggregation pass the pipeline agg
to the MongoTemplate#aggregate
method.
这篇关于Spring Data 中的 MongoDB $addField 和 $indexOfArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!