英文:
How can I code this Aggregate MongoDB query in Java?
问题
我有这个MongoDB查询:
db.collection.aggregate([
{
$set: {
AllSeasons: {
$concatArrays: [
"$Seasons",
[ "Last season" ],
[ "Last season 2" ]
]
}
}
},
{ $set: { average: { $avg: "$AllSeasons.goals" } } }
])
我想在Java中编写这个查询。我尝试了几次,但在$concatArrays处没有获得错误,并且无法解决它。
这是我尝试过的代码:
AggregateIterable<Document> doc = coll.aggregate(Arrays.asList(
new Document("$set", new Document("AllSeasons", new Document("$concatArrays", Arrays.asList("$Seasons", Arrays.asList("Last season"), Arrays.asList("Last season 2"))))),
new Document("$set", new Document("Average", new Document("$avg", "$AllSeasons.goals")))));
那么,我该如何在Java中编写这个查询呢?
非常感谢!
英文:
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!
答案1
得分: 2
希望Mongo查询正常工作。您可以使用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();
}
英文:
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();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论