【问题标题】:MongoDB $addField and $indexOfArray in Spring DataSpring Data 中的 MongoDB $addField 和 $indexOfArray
【发布时间】:2021-04-01 15:52:50
【问题描述】:

我正在尝试根据 Asya Kamsky 的post 使用 MongoDB 和 Spring Data 实现自定义排序:

List<AggregationOperation> operations = new ArrayList<>();

operations.add(Aggregation.addFields().addField("scorrrz")
        .withValueOfExpression("{ \"$indexOfArray\" : [ [\"John\", \"Bill\"], \"$name\" ] }").build());

当我尝试执行此操作时,我得到:

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 怎么做?

【问题讨论】:

    标签: mongodb spring-data aggregation-framework spring-data-mongodb


    【解决方案1】:
    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 上运行良好。

    运行此聚合将管道agg 传递给MongoTemplate#aggregate 方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-17
      • 2020-07-27
      • 2015-07-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多