In short this is the way:
var aggregation = newAggregation(
Application.class,
project().and(ObjectOperators.valueOf("applicants.people")
.toArray())
.as("people"));
mongoTemplate.aggregate(aggregation, Application.class, OutputModel.class);
it will generate for you an aggregation with following stage:
[
{
"$project": {
"people": {
"$objectToArray": "$applicants.people"
}
}
}
]
DETAILS
Assume that you have following model:
@Document(collection = "application")
@TypeAlias(alue = "application")
@AllArgsConstructor // lombok annotation
public class Application {
String id;
Applicants applicants;
@Value // lombok annotation
public static class Applicants {
Map<String, Person> people;
}
@Value
public static class Person {
PersonName personName;
boolean disabled;
}
@Value
public static class PersonName {
String firstName;
String lastName;
}
}
Example of documents in MongoDB for above can be:
{
"_id" : "id-1",
"applicants" : {
"people" : {
"person1" : {
"personName" : {
"firstName" : "Ziemowit",
"lastName" : "Stolarczyk"
},
"disabled" : true
},
"person2" : {
"personName" : {
"firstName" : "Denio",
"lastName" : "Pimentel"
},
"disabled" : false
}
}
},
"_class" : "application"
}
Generated projection by code from top will give you as an output:
{
"_id" : "id-1",
"people" : [
{
"k" : "person2",
"v" : {
"personName" : {
"firstName" : "Denio",
"lastName" : "Pimentel"
},
"disabled" : false
}
},
{
"k" : "person1",
"v" : {
"personName" : {
"firstName" : "Ziemowit",
"lastName" : "Stolarczyk"
},
"disabled" : true
}
}
]
}