Search code examples
mongodbmongodb-queryaggregation-frameworkmongo-shell

Get id value after aggregating pipeline


Consider following data in a collection named sample

{ "_id" : 1, "student_id" : 10, "type" : "homework", "score" : 63 },
{ "_id" : 3, "student_id" : 10, "type" : "homework", "score" : 14 },
{ "_id" : 2, "student_id" : 10, "type" : "quiz", "score" : 31 },
{ "_id" : 4, "student_id" : 10, "type" : "quiz", "score" : 54 },
{ "_id" : 5, "student_id" : 11, "type" : "homework", "score" : 33 },
{ "_id" : 7, "student_id" : 11, "type" : "homework", "score" : 74 },
{ "_id" : 6, "student_id" : 11, "type" : "quiz", "score" : 51 },
{ "_id" : 8, "student_id" : 11, "type" : "quiz", "score" : 24 }

I want to get the _id of minimum score obtained by each student in homework type.

I have the following query

db.sample.aggregate([
    {   $match: {   type: 'homework' }, },
    {
        $group: {
            _id: {
                student_id: '$student_id',
            },
            mark: {
                $min: '$score',
            }
        }
    }
])

which calculates the minimum mark, but I want the corresponding _ids.

the result of the above query is

{ "_id" : { "student_id" : 11 }, "mark" : 33 }
{ "_id" : { "student_id" : 10 }, "mark" : 14 }

Is it the right approach to get the ids.


Solution

  • Use $first with $sort ascending instead of $min to pull in the whole document ($$ROOT) with lowest score and map required fields.

    db.col.aggregate([
      {"$match":{"type":"homework"}},
      {"$sort":{"score":1}},
      {"$group":{
        "_id":"$student_id",
        "doc":{"$first":{"score":"$$ROOT.score","_id":"$$ROOT._id"}}
      }}
    ])