MongoDB Java 分组求和排序 | 使用聚合框架进行数据分析
在 MongoDB 中,可以使用聚合框架来对数据进行分组,求和和排序。以下是一个 Java 代码模板:
MongoClient mongoClient = new MongoClient( 'localhost' , 27017 ); // 连接 MongoDB 数据库
MongoDatabase database = mongoClient.getDatabase('mydb'); // 选择数据库
MongoCollection<Document> collection = database.getCollection('mycollection'); // 选择集合
// 创建聚合管道
List<Document> pipeline = Arrays.asList(
new Document('$group', new Document('_id', '$field')
.append('total', new Document('$sum', '$value'))),
new Document('$sort', new Document('total', -1)));
AggregateIterable<Document> result = collection.aggregate(pipeline); // 执行聚合查询
for (Document doc : result) { // 遍历查询结果
System.out.println(doc.toJson());
}
mongoClient.close(); // 关闭 MongoDB 连接
在上面的代码中,我们首先连接到 MongoDB 数据库,然后选择要操作的数据库和集合。接下来,我们创建一个聚合管道,该管道包括两个阶段:
$group阶段按field字段分组,并计算每个分组的value字段之和,将结果存储在total字段中。$sort阶段按total字段降序排序。
最后,我们执行聚合查询并遍历结果。在实际使用中,可以根据需要调整聚合管道中的阶段和参数。
原文地址: https://www.cveoy.top/t/topic/obGJ 著作权归作者所有。请勿转载和采集!