javamongodbspring-bootspring-data-mongodbmongotemplate

Aggregation Java MongoDB with MongoTemplate not return group value


In my Spring Controller I cannot figure out how to retrieve correctly the result of a MongoDB with MongoTemplate aggregation. Below is the code from my Controller class:

Aggregation aggregation = Aggregation.newAggregation(
                    Aggregation.match(Criteria.where("modality").is("check")),
                    Aggregation.group("name").count().as("check_count"),
                    Aggregation.project("name").and("check_count").as("check_count")
            );
            AggregationResults<Response> res = mongoTemplate.aggregate(aggregation, "user", Response.class);

Below the simple class of User and Response:

@Document(collection = "user")
class User{
     @Id
    private String id;
    private String name;
    private String modality;

   //constructor and get/set
}


class Response{
    private String name;
    private string check_count;

//constructor and get/set
}

So I retrieve correctly my response but I do not see the name, that is always null:

{
    "user": [
        {
            "name": null,
            "check_count": 61
        },
        {
            "name": null,
            "check_count": 15
        },...

What is wrong in my Aggregation.group ? Thanks


Solution

  • When you do the group aggregation, the pipeline that gets generated is mostly

    { "$group" : { "_id" : "$name", "check_count" : { "$sum" : 1}}}
    

    So, the result of the group stage will have _id as the field, not name. Subsequent, stage should use _id field.

    Aggregation.project().and("_id").as("name").and("check_count").as("check_count");