MongoDB 使用 MongoTemplate 进行分组查询去重
在 MongoTemplate 中,可以使用 Aggregation 操作实现分组查询和去重。
首先,你需要创建一个 AggregationOperation 对象,用于定义聚合操作的步骤。然后,通过 MongoTemplate 的 aggregate 方法执行聚合操作。
以下是一个示例代码,演示如何使用 Aggregation 操作实现分组查询和去重:
AggregationOperation groupBy = Aggregation.group('fieldToGroupBy').first('$$ROOT').as('doc');
AggregationOperation replaceRoot = Aggregation.replaceRoot('doc');
Aggregation aggregation = Aggregation.newAggregation(groupBy, replaceRoot);
AggregationResults<Document> results = mongoTemplate.aggregate(aggregation, 'collectionName', Document.class);
List<Document> distinctDocuments = results.getMappedResults();
在上述示例中,'fieldToGroupBy' 是用于分组的字段名,'collectionName' 是你要查询的集合名。
在聚合操作中,'$$ROOT' 用于保存整个文档,'first('$$ROOT')' 用于获取第一个文档,'as('doc')' 将结果保存到名为'doc' 的字段中。
然后,使用'replaceRoot' 操作将'doc' 字段作为根文档。
最后,使用'aggregate' 方法执行聚合操作,并通过'getMappedResults' 方法获取结果。
注意:在上述示例中,结果以 Document 对象的形式返回,你可以根据需要自行转换为其他类型。
原文地址: https://www.cveoy.top/t/topic/jLoG 著作权归作者所有。请勿转载和采集!