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