数据分组:
db.raw_data.aggregate([
{$group: {"_id": "$articleNo", "count":{$sum:1}}}
])
结果:_id是分组的字段值,count是每一个值的总数

java代码:
包:spring-data-mongodb-2.1.4.RELEASE.jar
Aggregation aggregation = Aggregation.newAggregation(
Aggregation.match(criteria),// 条件
Aggregation.group("articleNo").count().as("count")// 分组统计
);
AggregationResults<JSONObject> result = mongoTemplate.aggregate(aggregation, "raw_data",JSONObject.class);
List<JSONObject> list= result.getMappedResults();
结果是:[{
"_id":"526215",
"count":"3"
}]
多重分组
db.raw_data.aggregate([
{$group: {"_id": "$articleNo"}},
{$group: {"_id": 1, "count":{$sum:1}}},
])
第一次分组是按照某些条件分组,第二次是统计分组后,所有分组的总数,相当于去重后计算总数。
结果:count总数,就是刚刚分组后的数据,计算了他的总数。

java代码:
Aggregation aggregation = Aggregation.newAggregation(
Aggregation.match(criteria),
Aggregation.group("articleNo").sum("_id").as("articleNo"),// 先按照字段分组, sum的值是_id,是因为分组后,默认分组的值的key是_id.
Aggregation.group("articleNo").count().as("count") //计算分组后数据的总数
);
AggregationResults<JSONObject> result = mongoTemplate.aggregate(aggregation, "raw_data",JSONObject.class); List<JSONObject> list= result.getMappedResults();
结果:
[{
"_id":"1",
"count":"7"
}]
分组分页查询:
Aggregation aggregation2 = Aggregation.newAggregation(
Aggregation.match(criteria),
Aggregation.group(SizeTableConstants.ARTICLE_NO).count().as("count")
.first("operator").as("operator").first("language").as("language")
.first("updateTime").as("updateTime"),
Aggregation.sort(new Sort(Sort.Direction.DESC, "updateTime")),
Aggregation.skip(5L),
Aggregation.limit(10L)
);
//得到结果集
AggregationResults<JSONObject> results = mongoTemplate.aggregate(aggregation2, "raw_data",JSONObject.class);
List<JSONObject> list= results.getMappedResults();
关于分组后,如何展示需要的字段,目前是使用first,一个一个列出来的,不知道有没有其他更好的方式。
本文介绍了如何使用MongoDB的aggregate方法进行数据分组,包括单重分组计算总数,以及多重分组实现去重计数。在Java环境下,通过spring-data-mongodb库实现了相关操作,最后探讨了分组后如何进行分页查询,提出了目前采用的first方法来获取所需字段,但寻求更优解决方案。
3758

被折叠的 条评论
为什么被折叠?



