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

我想为每个文档找到字段 scores.score where 的最小值score.type = "homework"

我执行了这样的查询

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

mongo shell 返回此错误

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() 会简单地将您的结果限制在使用索引的下限之上。而是尝试使用聚合()。

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 回答