需求背景:
集合‘matchs_info’中存在一个叫做’yyyymmdd’的字段,字段内容为String类型的日期格式。
想要对该字段进行分组,这样的话就能查到这个集合中有多少个日期数据。
网上查了两个小时,可算找到了办法。
实现:
需要用到的对象有mongoTemplate以及Aggregation。
public void groupOfMongodb(){
Aggregation aggregationObj = Aggregation.newAggregation(Aggregation.group("yyyymmdd").count().as("总数"));
//第一个参数'group'为你要分组的字段,count()方法为统计该字段存在着相同重复的值有多少个,第二个参数'as'为结果的自定义别名。
List<String> mappedResults = mongoTemplateObj.aggregate(aggregationObj, "matchs_info", String.class).getMappedResults();
//'matchs_info'为你的集合名,'String.class'为接受分组结果的类型。你也可以选择其它类型。
System.out.println(mappedResults);
}
很显然,上面的代码不完全符合我的需求标准.假若你也只想获取传统的,以该字段下不同数值为基准的分组结果,那么可以参考我下面的代码
public void groupOfMongodb(){
Aggregation aggregationObj = Aggregation.newAggregation(Aggregation.group("yyyymmdd"));
List<Map> mappedResults = mongoTemplateObj.aggregate(aggregationObj, "matchs_info", Map.class).getMappedResults();
System.out.println(mappedResults);
for (int i = 0; i < mappedResults.size(); i++) {
String value = (String)mappedResults.get(i).get("_id");
System.out.println(value);
}
}
参考:
https://blog.csdn.net/u010831352/article/details/73498518?utm_medium=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param