Search code examples
mongodbmongodb-queryaggregation-frameworkmongodb-aggregation

Issue with $group command in MongoDB


I'm having an issue with Mongo DB where I am trying to group results using the command below. This maps to a Java object containing fields id, name and a list of results. However the name attribute will not map correctly for me.The $name attribute does exist in the document, so I'm not sure what is causing the problem. If anyone can point me in the right direction it would be appreciated.

{
    "$group": {
    "_id": "$testCaseId",
         "name": "$name",
         "results": {
              "$push": {
                   "testCaseId": "$testCaseId",
                   "executionId": "$executionId",
                   "resultCode": "$resultCode",
                   "time": "$time"
               }
          }
     }
}

Here is the structure of the Java object I am mapping to:

private String id;
private String name;
private List<Results> results;

And id and results are being populated correctly (if I remove name), however when I include name, I get this exception:

"exception: the group aggregate field 'name' must be defined as an expression inside an object".


Solution

  • Please use group accumulation operators like $first or $last.

    $first: Returns a value from the first document for each group. $last: Returns a value from the last document for each group.

    {
        "$group": {
            "_id": "$testCaseId",
            "name": {"$first" : "$name"},
            "results": {
                "$push": {
                    "testCaseId": "$testCaseId",
                    "executionId": "$executionId",
                    "resultCode": "$resultCode",
                    "time": "$time"
                }
            }
        }
    }