Pillola: Spring Data Mongodb, oggetto con campi multipli in push di grouping
Problema
Come traduco in Spring Data MongoDB la seguente query che aggiungere oggetti con due o più campi all’array ottenuto tramite grouping
db.getCollection('measure').aggregate([
{
$sort: { date : -1 }
},
{
$group: {_id: "$zone", metrics: { $push: {date: "$date", length: "$length"}}}
}
])
Soluzione
Utilizzando un BasicBSONObject
come parametro del metodo push
List<AggregationOperation> operations = new ArrayList<>();
operations.add(Aggregation.sort(Direction.DESC, "date"));
Fields groupByFields = Fields.from(Fields.field("zone"));
AggregationOperation group = Aggregation.group(groupByFields)
.push(new BasicBSONObject("date", "$date").append("length", "$length")).as("metrics");
operations.add(group);
Aggregation aggregation = Aggregation.newAggregation(operations);
AggregationResults<Metrics> result = mongo.aggregate(aggregation, MeasureDocument.class, Metrics.class);