一、普通求总数
db.sendlog.find({"event":1000000000001}).count()
二、分组统计并求最大时间
db.sendlog.group({
key:{template:"$template",event:"$event",channel:"$channel"},//根据mongodb中的字段分组
initial: { failureNum:0,failureSendTime:"1990-01-01 00:00:00" },//初始化字段
cond: { event: 1000000000001 ,success:"1"},//条件筛选
reduce: function ( curr, result) {
result.failureNum++;//数量统计
if(curr.failureSendTime>result.failureSendTime){
result.failureSendTime=curr.failureSendTime;//求最大失败时间
}
}
,
finalize: function(result) {
}
}
)
由于是公司数据库,真正字段就不显示了,直接对应上方的字段匹配
三、在java中用mongotemplate进行查询
1.导包
<!--mongodb -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
2.写配置
spring.data.mongodb.uri=mongodb://用户名:密码@IP:端口/数据库名
例如:
spring.data.mongodb.uri=mongodb://user:pwd@127.0.0.1:27017/log
3.代码
@Autowired
private MongoTemplate mongoTemplate;
/**
* 查询统计发送失败数据
*/
public List<MessageEventStatistic> querySuccessStatistic(Long eventId ) {
Criteria criteria=Criteria.where("event").is(eventId).and("success").is("1");
GroupByResults<MessageEventStatistic> group = mongoTemplate.group(
criteria,
"msgSmsSendLog",
new GroupBy("event","template", "channel")
.initialDocument("{ failureNum: 0 ,failureSendTime:\"1990-01-01 00:00:00\"}")
.reduceFunction("function(curr, result){ result.failureNum++; if(curr.failureSendTime>result.failureSendTime){ result.failureSendTime=curr.failureSendTime; }}"),
MessageEventStatistic.class);//返回接收类,记得返回的字段要和类的字段一致
Iterator<MessageEventStatistic> iterator = group.iterator();
List<MessageEventStatistic> list=new ArrayList<>();
while(iterator.hasNext()){
MessageEventStatistic next = iterator.next();
next.setSuccessSendTime(DateUtil.parseTime(next.getSuccessSendTimeStr()));
list.add(next);
System.out.println(next.toString());
}
return list;
}