Spring MongoDB: map a string-array to an Object-Array

Viewed 309

I have a document like this one:

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

and I want to show my result in this way:

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

I used a Projection like this one:

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

and it works!!! Maybe this is not the best solution, but it works.

My problem is to convert this code in Java with Spring-MongoDB.

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

How can I create an AggregationExpression that maps an Object with the keys name and index?

1 Answers

The synthax for the Array reduce is like this:

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()));
Related