0

私のコレクションには、このようなドキュメントがあります

{ "_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 } ] }

各ドキュメントについて、フィールド score.score の最小値を見つけたいと思いますscore.type = "homework"

このようなクエリを実行しました

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

mongo シェルはこのエラーを返します

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
}
4

1 に答える 1

0

これには、find() を min() と一緒に使用しないでください。min() は、インデックスを使用して結果を下限を超えるものに単純に制限します。代わりに、aggregate() を使用してみてください。

db.students.aggregate([
    {
        $unwind:"$scores"
    },
    {
        $match: {"scores.type":"homework"}
    },
    {
        $group:{
            _id: {
                _id:"$_id",
                name: "$name"
            },
            min_score: {$min: "$scores.score"}
        }
    }
]);
于 2016-08-17T09:25:07.783 に答える