如何通过MongoDB Java API统计去重字段的数量?
无需迭代获取MongoDB去重字段值数量的方法
嘿,这个问题我之前也踩过坑!确实MongoCollection.distinct()返回的DistinctIterable没有直接获取数量的size()方法,手动迭代统计不仅代码啰嗦,数据量大的时候还会占用客户端内存。给你分享两个更高效的解决方案:
方法一:使用聚合框架(推荐,性能最优)
这个方法是让数据库端直接计算去重后的数量,不用把所有去重数据拉到客户端,适合数据量较大的场景。代码示例如下:
import com.mongodb.client.MongoCollection; import com.mongodb.client.model.Aggregates; import org.bson.Document; import java.util.Arrays; // 获取集合 MongoCollection<Document> collection = db.getCollection("test"); // 聚合管道:先按name字段分组,再统计分组数量 AggregateIterable<Document> aggregateResult = collection.aggregate(Arrays.asList( Aggregates.group("$name"), // 按name字段分组,自动完成去重 Aggregates.count() // 统计分组总数,也就是去重后的字段值数量 )); // 取出最终统计结果 Document countDocument = aggregateResult.first(); int distinctCount = countDocument.getInteger("count");
这个方式的核心是把计算逻辑放在数据库端执行,客户端只需要接收最终的统计数字,性能比拉取所有去重数据要高得多。
方法二:用into()方法将结果存入集合后获取size
如果你觉得聚合框架有点复杂,也可以用DistinctIterable的into()方法,把去重结果直接存入一个List,然后通过List的size()获取数量,代码更简洁:
import com.mongodb.client.MongoCollection; import java.util.ArrayList; import java.util.List; MongoCollection<Document> collection = db.getCollection("test"); List<String> distinctNames = new ArrayList<>(); // 将去重后的name值批量存入List collection.distinct("name", String.class).into(distinctNames); // 直接获取List的大小就是去重后的数量 int count = distinctNames.size();
这个方法虽然还是会把所有去重数据拉到客户端,但比手动写迭代循环要简洁很多,适合数据量不大的场景。
小提示
尽量优先用聚合框架的方式,尤其是当你的集合数据量很大的时候,避免把大量数据加载到客户端内存中,导致性能问题。
内容的提问来源于stack exchange,提问作者Saravanakumar Murugesan
相关产品推荐
相关产品推荐

