将mongodb聚合查询转换为Java/Kotlin Spring数据



所以我提出了一个查询,我真的不知道如何转换为Spring Data。这是一个查询:

db.collection.aggregate([{
{
$group: {
_id: "$field",
count: {
$sum: "$count"
},
data: {
"$addToSet": "$$ROOT"
}
}
},
{
$sort: {
count: -1
}
},
{
$limit: 10
},
{
$unwind: "$data"
}
])

有问题的部分是unwind。在这个原始查询中,我将正在处理的原始文档("$$ROOT"(放入data中,因此在处理集合之后,我可以将其展开,最终只得到我真正想要的文档。这在外壳中运行良好。问题是,我看不到如何在Java/Kotlin中执行相同的操作,我可以直接添加到集合中,而无需稍后引用该数据。有人能帮我写下这在Java/Kotlin和Spring Data中的样子吗?

你可以试试这个

public List<Object> test() {
Aggregation aggregation = Aggregation.newAggregation(

group("field")
.sum("count").as("count")
.addToSet("$$ROOT").as("data"),
sort(Sort.Direction.DESC, "count"),
limit(10),
unwind("data")
).withOptions(AggregationOptions.builder().allowDiskUse(Boolean.TRUE).build());
return mongoTemplate.aggregate(aggregation, mongoTemplate.getCollectionName(YOUR_COLLECTION.class), Object.class).getMappedResults();
}

最新更新