Reputation: 65
I have this MongoDB query:
db.collection.aggregate([
{
$set: {
AllSeasons: {
$concatArrays: [
"$Seasons",
[ "$Last season" ],
[ "$Last season 2" ]
]
}
}
},
{ $set: { average: { $avg: "$AllSeasons.goals" } } }
])
I want to code this query in Java. I have made several attempts but I don't get an error with $concatArrays and can't resolve it.
This is what I tried:
AggregateIterable<Document> doc = coll.aggregate(Arrays.asList(
new Document("$set", new Document("AllSeasons", new Document("$concatArrays", "[$Seasons, ['$Last season'] , ['$Last season 2']] "))),
new Document("$set", new Document("Average", new Document("$avg", "$AllSeasons.goals")))));
So how do I code this query in Java?
Thank you so much!
Upvotes: 1
Views: 741
Reputation: 8894
Hope the mongo query is working. And you can go with mongoTemplate
public List<Object> test(){
Aggregation aggregation = Aggregation.newAggregation(
a-> new Document("$set",
new Document("AllSeasons",
new Document("$concatArrays",
Arrays.asList("$Seasons",Arrays.asList("$Last_season_1"),Arrays.asList("$Last_season_2"))
)
)
),
b-> new Document("$set",
new Document("average",
new Document("$avg","$AllSeasons.goals")
)
)
).withOptions(AggregationOptions.builder().allowDiskUse(Boolean.TRUE).build());
return mongoTemplate.aggregate(aggregation, mongoTemplate.getCollectionName(YOUR_COLLECTION.class), Object.class).getMappedResults();
}
Upvotes: 2