1

I'm forced to use the aggregation framework and the project operation of Spring Data MongoDb.

What I'd like to do is creating an array of object as a result of a project operation.

For example, considering this intermediate aggregation result:

[
  {
    "content": {
      "processes": [
        {
          "id": "101a",
          "title": "delivery"
        },
        {
          "id": "101b",
          "title": "feedback"
        }
      ]
    }
  }
]

What I want to obtain is this:

[  
  {
    "results":
    {
      "titles": [
        {
          "id": "101a",
          "value": "delivery"
        },
        {
          "id": "101b",
          "value": "feedback"
        }
      ]
    }
  }
]

This was just an example, I don't want to simply "rename" some fields. What I want is the possibility to create an array of objects.

If I try something like this:

   projectionOperation
     .and("$content.processes.id").as("results.titles.id")
     .and("$content.processes.title").as("results.titles.value");

I obtain this:

[  
  {
    "results":
    {
      "titles": {
          "id": ["101a", "101b"]
          "value": ["delivery", "feedback"]
        }
      }
    }
  }
]

With this projection the array is created, but not "in the proper position".

However, If I use the nested operator, I haven't figure out a way to specify that I want to create an array instead of an object. With this projection:

projectionOperation.and("results.titles")
         .nested(
              bind("id", "process.id")
                 .and("value", "process.title")
         );

I can create a proper nested object but not into an array:

"results.titles": {
            "id": "101b",
            "value": "feedback"
        }
desoss
  • 572
  • 4
  • 26
  • 1
    Can you show us the java code that you have tried ? – s7vr Aug 17 '18 at 13:18
  • @Veeram I've updated the question – desoss Aug 20 '18 at 09:30
  • I've tried to use arrayOf(), projectOperation.and(arrayOf("results.titles")).nested(bind(...)), without any luck – desoss Aug 20 '18 at 09:43
  • Hi @Veeram , I've added a similar question. I would appreciate a lot if you could take a look. It's https://stackoverflow.com/questions/52492829/cannot-use-nested-variableoperators-mapitemsof-in-spring-data-mongodb – desoss Sep 25 '18 at 15:18

1 Answers1

2

You can try below aggregation code.

ProjectionOperation po = Aggregation.project().and(
   VariableOperators.mapItemsOf("content.processes").as("rt")
    .andApply(
      new AggregationExpression() {
       @Override
       public Document toDocument(AggregationOperationContext aggregationOperationContext) {
             return new Document("id", "$$rt.id").append("value", "$$rt.title");
       }
    } 
  )
).as("result");
s7vr
  • 73,656
  • 11
  • 106
  • 127