mongodb中aggregate分组统计

1.文档结构java

{
    "_id" : "5d5e5dd8cd14441aec8bc4a2",
    "status" : "0",
    "createTime" : "2019-08-22T09:18:16.560Z",
    "data" : {
        "code" : "281",
        "type" : "yuwen",
        "count" : 5,
        "userId" : "123"}
}

2.全表统计
db.getCollection('test').aggregate([{                                                          
    "$match": {}}, {                                                                                         
    "$group": {                                                                                              
        "_id": {"code":"$data.code","language":"$data.type"},"count":{"$sum":1}
    }                                                                                                        
}])
说明:根据code,type分组统计记录数量,"$match": {}无查询条件,可忽略。根据$data.code、$data.type分组,使用$表示引用文档中的属性。app

3.java代码示例spa

public List<Map<String, Object>> getStatTest(String status) {
    Aggregation aggregation = Aggregation.newAggregation(
            Aggregation.match(Criteria.where("status").is(status)),
            Aggregation.group("data.code", "data.type")
                    .count().as("count")
                    .sum(ConditionalOperators.when(Criteria.where("data.count").gte(5)).then(1).otherwise(0)).as("dataCount")
    );

    AggregationResults<Map> ar = mongoTemplate.aggregate(aggregation, Test.class, Map.class);
    Object obj = ar.getMappedResults();
    List<Map<String, Object>> result = (List<Map<String, Object>>) obj;

    return result;
}

说明:ConditionalOperators为条件表达式 if(data.count>=5){ sum=1) else { sum=0} 计算记录中count>5的总数code

参考文档:https://www.iteye.com/blog/shift-alt-ctrl-2259216blog

相关文章
相关标签/搜索