在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的原生文档类,您可以根据自己的需求替换为适当的实体类。

mongoTemplate如何查询并按字段去重

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

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