如何在Morphia 2.3中用datastore.aggregate()实现分组统计count(*)
在Morphia 2.3中实现分组统计(类似SQL GROUP BY + COUNT(*))
要实现类似SQL select count(*) from table group by name; 的分组统计功能,对应MongoDB的聚合逻辑是按name字段分组,通过$sum:1统计每组文档数量。在Morphia 2.3中可以通过datastore.aggregate()这样实现:
核心实现代码
Java版本
// 定义聚合结果的实体类 public class GroupCountResult { @Id private String name; // 对应分组的_id(即name字段的值) private long totalCount; // 每组的统计数量 // 生成getter、setter方法,或使用Lombok简化 } // 执行聚合查询 List<GroupCountResult> countResults = datastore.aggregate(YourEntity.class) // 按name字段分组,对应MongoDB的$group._id: "$name" .group(group(id(field("name"))) // 统计每组数量,对应MongoDB的$sum:1 .field("totalCount", sum(1))) .execute(GroupCountResult.class) .toList();
Kotlin版本
// 定义聚合结果的数据类 data class GroupCountResult( @Id val name: String, // 对应分组的_id val totalCount: Long // 每组的统计数量 ) // 执行聚合查询 val countResults = datastore.aggregate(YourEntity::class.java) .group(group(id(field("name"))) .field("totalCount", sum(1))) .execute(GroupCountResult::class.java) .toList()
关键说明
- 分组依据:
group(id(field("name")))指定以实体中的name字段作为分组键,对应MongoDB聚合管道中的_id: "$name"。 - 统计逻辑:
sum(1)对应MongoDB的$sum:1,用于统计每组内的文档总数。注意这里要传入数值1,而非字符串"1"(原代码中的写法有误)。 - 结果映射:聚合结果中的
_id会自动映射到结果类中用@Id标注的属性,totalCount则对应聚合中定义的统计字段名。
可选:添加过滤条件
如果需要先过滤数据再分组统计,可在group()前添加match():
// Java示例:仅统计name不为空的文档 List<GroupCountResult> filteredResults = datastore.aggregate(YourEntity.class) .match(criteria("name").exists(true)) .group(group(id(field("name"))).field("totalCount", sum(1))) .execute(GroupCountResult.class) .toList();
内容的提问来源于stack exchange,提问作者Kassutta Fit
相关产品推荐
相关产品推荐

