对文档 entryStat 进行统计
按照 shareTpye 筛选后的数据
通过key 进行 mapreduce
类似 sql 的
select id ,count(1)
from entryStat
where shareType = #{shareType }
groupby id
代码如下
public List<EntryStatMrResult> listEntryStat(int shareType){
Query query = new Query(Criteria.where("shareType").is(shareType));
MapReduceResults<EntryStatMrResult> mapReduceResults = mongoTemplate.mapReduce(
query,
"entryStat",
"classpath:map.js",
"classpath:reduce.js",
EntryStatMrResult.class);
return Lists.newArrayList( mapReduceResults.iterator());
}
文档的数据类型是
@Getter
@Setter
public class EntryStat implements Serializable {
@Id
public String id;
public String userId;
public String userName;
public Integer shareType ;
public Date createTime;
public Date updateTime;
}
返回类型
@Data
public class EntryStatMrResult {
private String id;
private Integer value;
}
map.js
function map() {
emit(this.userId,1);
}
reduce.js
function reduce(key, values2) {
var sum = 0;
for (var i = 0; i < values2.length; i++)
sum += values2[i];
return sum;
}
mongo 依赖
<!--mongodb依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
</dependency>
参考文档
https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/
https://docs.mongodb.com/manual/tutorial/map-reduce-examples/
网友评论