Search code examples
mongodbembedded-documents

Error executing a mongodb query with cursor.min with embedded documents


In my collection there are documents like this

{ "_id" : 112, "name" : "Myrtle Wolfinger", "scores" : [ { "type" : "exam", "score" : 73.93895528856032 }, { "type" : "quiz", "score" : 35.99397009906073 }, { "type" : "homework", "score" : 93.85826506506328 }, { "type" : "homework", "score" : 71.21962876453497 } ] }

I want to find for each document the min of the field scores.score where score.type = "homework".

I executed a query like this

db.students.find({},{"scores.score":1}).min( { "scores.type":"homework" } )

mongo shell returns this error

error: {
    "$err" : "Unable to execute query: error processing query: ns=school.students limit=0 skip=0\nTree: $and\nSort: {}\nProj: { scores.score: 1.0 }\n planner returned error: unable to find relevant index for max/min query",
    "code" : 17007
}

Solution

  • You wouldn't use find() with min() for this. min() would simple limit your results to those above a lower bound using an index. Instead try using aggregate().

    db.students.aggregate([
        {
            $unwind:"$scores"
        },
        {
            $match: {"scores.type":"homework"}
        },
        {
            $group:{
                _id: {
                    _id:"$_id",
                    name: "$name"
                },
                min_score: {$min: "$scores.score"}
            }
        }
    ]);