mongodbspring-data-mongodb

How to use mongodb Aggregation.addFields() reduce?


I want to convert the following code into spring data mongodb code.

[
  {
    $addFields: {
      children: {
        $reduce: {
          input: "$children",
          initialValue: {
            level: -1,
            presentChild: [],
            prevChild: []
          },
          in: { $concat : ["$$value", "$$this"] }
        }
      }
    }
  }
]

I tried the following:

val agg = newAggregation(
    Aggregation.addFields()
        .addField("children")
        .withValueOf(
            ArrayOperators.Reduce.arrayOf("children").withInitialValue(
                mapOf(
                    "level" to -1,
                    "presentChild" to emptyList<Any>(),
                    "prevChild" to emptyList<Any>()
                )
            )
        ).build()
)

output:

[
  {
    $addFields: {
      children: {
        val$initialValue: {
          level: -1,
          presentChild: [],
          prevChild: []
        }
      }
    }
  }
]

This is not the expected result.

I searched the web but found nothing.

what should I do?


Solution

  • Both your query and Java code is missing in expression. It should look something like this.

    Aggregation.addFields().addField("children")
        .withValueOf(
            ArrayOperators.Reduce.arrayOf("children")
            .withInitialValue(<initialValue>)
            .reduce(StringOperators.Concat.valueOf(ArrayOperators.Reduce.Variable.VALUE.getTarget())
                .concat(ArrayOperators.Reduce.Variable.THIS.getTarget())
            )
        ).build();
    

    Replace the placeholders with your appropriate initial value and reduction expressions.