【问题标题】:Spring MongoDB: map a string-array to an Object-ArraySpring MongoDB:将字符串数组映射到对象数组
【发布时间】:2021-08-16 14:21:17
【问题描述】:

我有这样一份文件:

{
  "steps": ["step 1", "step 2"]
}

我想以这种方式展示我的结果:

{
  "steps": [
    {"name": "step 1", "index": 1},
    {"name": "step 2", "index": 2}
  ]
}

我用过这样的投影:

{
  "$project": {
    "steps": {
      $reduce: {
        input: "$steps",
        initialValue: [],
        in: {$concatArrays: [
          "$$value", 
          [{"name": "$$this", "index": {$add: [1, {$size: "$$value"}]}}]
        ]}
      }
    }
  }
}

它的工作原理!也许这不是最好的解决方案,但它确实有效。

我的问题是用 Spring-MongoDB 在 Java 中转换这段代码。

var reduce = ArrayOperators.arrayOf("steps")
  .reduce(
    ArrayOperators.arrayOf("$$value").concat( ??? ))                               
  .startingWith(Collections.EMPTY_LIST);

如何创建一个 AggregationExpression 来映射具有键 nameindex 的对象?

【问题讨论】:

    标签: java mongodb spring-data


    【解决方案1】:

    Array reduce 的合成器是这样的:

    ArrayOperators.Reduce reduce = ArrayOperators.Reduce
                    .arrayOf("$steps")
                    .withInitialValue(new ArrayList())
                    .reduce(ArrayOperators.ConcatArrays.arrayOf(ArrayOperators.Reduce.Variable.VALUE.getTarget())
                            .concat(ArrayOperators.Reduce.Variable.THIS.getTarget()));
    

    【讨论】:

      猜你喜欢
      • 2018-05-29
      • 1970-01-01
      • 2021-07-29
      • 2012-01-23
      • 2021-11-15
      • 2015-07-16
      • 1970-01-01
      • 2014-10-31
      • 1970-01-01
      相关资源
      最近更新 更多