在 MongoTemplate 中,可以使用 aggregate 方法进行查询并按字段去重。

以下是一个示例代码:

Aggregation aggregation = Aggregation.newAggregation(
    Aggregation.group('fieldName').first('$$ROOT').as('doc'),
    Aggregation.replaceRoot('doc')
);

List<Document> results = mongoTemplate.aggregate(aggregation, 'collectionName', Document.class).getMappedResults();

在上面的代码中,可以将 'fieldName' 替换为要去重的字段名,'collectionName' 替换为要查询的集合名称。

此代码将按指定字段进行分组,并使用 first 操作符选择每个分组的第一个文档作为结果。然后使用 replaceRoot 操作符将结果中的 'doc' 字段作为根文档。

最后,通过调用 getMappedResults() 方法获取查询结果。

请注意,上述代码中的 'Document' 类是 MongoDB 的原生文档类,您可以根据自己的需求替换为适当的实体类。

MongoDB 使用 MongoTemplate 按字段去重查询

原文地址: https://www.cveoy.top/t/topic/jLor 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录