spring-data-mongodb icon indicating copy to clipboard operation
spring-data-mongodb copied to clipboard

Reduce aggregation operation doesn't allow using Variable.VALUE and Variable.THIS with strict mapping

Open Cerber-Ursi opened this issue 2 years ago • 1 comments

I've attempted to execute the following aggregation operation:

{
  "names": {
    "$reduce": {
      "input": "$nestedNames",
      "initialValue": "$names",
      "in": {
        "$setUnion": [
          "$$value",
          "$$this"
        ]
      }
    }
  }
}

where the original structure is like this:

public class NamesLists {
  public List<String> names;
  public List<List<String>> nestedNames;
}

This, if I'm not mistaken, should correspond to the following Spring code:

AggregationOperation project = Aggregation.project()
    .and(
        ArrayOperators.Reduce.arrayOf("nestedNames")
            .withInitialValue(Fields.field("names"))
            .reduce(SetUnion.arrayAsSet(Variable.VALUE.getTarget()).union(Variable.THIS.getTarget()))
    )
    .as("names");

This, however, doesn't work with AggregationOptions.strictMapping(), since Variable.VALUE and Variable.THIS are converted into $$value and $$this correspondingly, and document obviously doesn't have these fields.

This aggregation works without strict mapping, since in this case the variable names are passed into the document as-is. However, this is merely masking the problem.


It's possible that I was just incorrectly using the variables. In this case, it's probably better to have the documentation changed, since currently it seems that the only references to them are in documentation for ReduceBuilder.Reduce.

Cerber-Ursi avatar May 31 '22 09:05 Cerber-Ursi

Got similar problem also with $map operation. The following code works (with the same base model) only without strict mapping:

AggregationOperation project = Aggregation.project()
    .and(
        VariableOperators.mapItemsOf("names")
            .as("name")
            .andApply(StringOperators.valueOf("$$name").lengthCP())
    )
    .as("ownersLength");

Otherwise, it fails with "No property '$$name'".

Cerber-Ursi avatar Jun 03 '22 11:06 Cerber-Ursi