Springboot mongodb implements grouping query operation

  mongodb, question

How to use mongodb in spring boot to implement grouping statistics queries such as group?
For example:Counting the number of people with the same name in each province in China, the data content is as follows:

{ "country" : "china", "province" : "sh", "userid" : "a" }
 {  "country" : "china", "province" : "sh", "userid" : "b" }
 {  "country" : "china", "province" : "sh", "userid" : "c" }
 {  "country" : "china", "province" : "bj", "userid" : "da" }
 {  "country" : "china", "province" : "bj", "userid" : "fa" }

The statistical results are: [{“country”: “China”, “provision”: “sh”, “count”: 3}, {“country”: “China”, “provision”: “BJ”, “count”: 2}]
Useaggregate([{ $group: {"_id": { "country" : "$country", "province": "$province" , "uid" : "$userid" } } } , { $group: {"_id": { "country" : "$_id.country", "province": "$_id.province" }, count : { $sum : 1 } } }])Mongdb gets the data correctly, how can it be implemented in springboot using java?

Implemented using aggregate query aggregation. Due to the characteristics of mongodb database, aggregation is usedPipelineOperation. (PS. group operation cannot return fields other than the specified fields)
A similar implementation includes the following steps:

Aggregation agg = Aggregation.newAggregation(
 //Step 1: Select the required fields, similar to the field contents represented by select *, *
 Aggregation.project("licensePlate", "companyName", "deviceCode", "diverName", "fleet", "lineNumber",
 "imgUrl", "videoUrl", "ptLoc", "locations"),
 //Step 2: sql where statement filters qualified records
 //Step 3: Group Conditions, Set Group Fields
 Aggregation.group("companyName", "licensePlate")
 . COUNT().as("allCount")// add count as the field output after grouping
 . last ("ptloc"). as ("ptloc"). last ("locations"). as ("locations")//add publishDate as the field to be output after grouping
 //Step 4: Re-select Fields
 Aggregation.project("diverName", "licensePlate", "companyName", "deviceCode", "allCount", "fleet",
 "lineNumber", "imgUrl", "videoUrl", "ptLoc", "locations")
 AggregationResults<HeatMap> results = mongoOperations.aggregate(agg, "Historys", HeatMap.class);
 List<HeatMap> list = results.getMappedResults();

The nature of pipeline execution is that each step is executed in sequence, and the operation result of the first step is passed to the next step, so the sequence of codes affects the final result. Therefore, to obtain other fields of the set after grouping, the fields to be returned should be specified in the first step and the last step.