我的数据库中有重复的行值,并且只想从 API 中获取 1。 例如在数据库中我有这种结构:
{
_id:39012fh19fh19bf21
"propertyId":12345,
"type":"STORE"
},
{
_id:69999999111
"propertyId":12345,
"type":"STORE"
}
唯一的区别是 MongoDB ID,其他属性相同。 我尝试使用不同的聚合进行分组,但无法弄清楚。
我的代码目前非常简单,如下所示:
val matchOperation = match(nestedCriteria) // Here are some criterias for basic filtering
val sortDirection = Sort.Direction.ASC
val sortBy = "type"
val page = PageRequest.of(...)
val aggregation = newAggregation(
matchOperation, sort(Sort.by(sortDirection, sortBy)), skip(page.offset), limit(
page.pageSize.toLong()
)
)
return mongoTemplate.aggregate(aggregation, "my_collection", MyCollectionVO::class.java)
.asFlow()
我尝试了一些像这样的东西和一堆其他组合,但它不起作用:\
val groupOperation = group("propertyId", "type")
.count().`as`("count")
.first("_id").`as`("uniqueDocId")
val matchOperation = match(Criteria.where("count").gt(1))
你只有_id的区别。因此,您需要使用 $group 并使用 $first 返回文档组中的第一个文档。
与 Mongo Playground 的查询: https://mongoplayground.net/p/29hiyjVLIop
var groupPipeline = group("$element").first("$$ROOT").as("doc");
var replaceRootPipeline = replaceRoot("doc");
var aggregation = newAggregation(groupPipeline, replaceRootPipeline);
mongoTemplate.aggregate(aggregation, "collection_Name", CollectionClass.class);