1

I'm trying to get one property from one array that has a bunch of properties in my document and put the result as a new array

This is a simple aggregation with map. I can do that with mongo in the shell by using the following query:

db.getCollection('foo').aggregate([ 
  { '$project': { 'newField': { '$map': { input: '$contacts', in: '$$this.email' } } }
])

I cannot create this in Java with Spring Mongo, though. I checked the documentation and I found this: https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mongo.aggregation.supported-aggregation-operations

I could create this with that info and the help of my IDE:

AggregationOperation project = Aggregation.project()
   .and(VariableOperators.Map.itemsOf("contacts")
   .as("c")
   .andApply(document -> new Document("newFieldArray", StringOperators.valueOf("c.email")))).as("newField")

but it returns null and on top of that it's very hard to debug. I keep seeing this in the debugger:

"includedDivisions" : { "$map" : { "input" : "$contacts", "as" : "c", "in" : { "c" : { "$java" : org.springframework.data.mongodb.core.aggregation.StringOperators$StringOperatorFactory@796460bf } } } },

Any help would be appreciated

renno
  • 2,659
  • 2
  • 27
  • 58

1 Answers1

0

Spring-data doesn't offer full support for Query DSL.

So, you need to extend AggregationOperation explained here and setup your raw query as BasicDBObject / Document (depending on your MongoDB version).

AggregationOperation project =
    new GenericAggregationOperation(
       "$project", 
       "{ \"newField\": { \"$map\": { \"input\": \"$contacts\", \"in\": \"$$this.email\" } } }"
);
Operations.aggregate(Aggregation.newAggregation(project), ...);
Valijon
  • 12,667
  • 4
  • 34
  • 67