如何在MongoDB中打印最小结果

时间:2012-11-19 23:25:08

标签: python mongodb

MongoDB noob here ...

所以,我正在尝试打印出看起来像这样的集合中的最小值得分......

        > db.students.find({'_id': 1}).pretty()
        {
                "_id" : 1,
                "name" : "Aurelia Menendez",
                "scores" : [
                        {
                                "type" : "exam",
                                "score" : 60.06045071030959
                        },
                        {
                                "type" : "quiz",
                                "score" : 52.79790691903873
                        },
                        {
                                "type" : "homework",
                                "score" : 71.76133439165544
                        },
                        {
                                "type" : "homework",
                                "score" : 34.85718117893772
                        }
                ]
        }

我正在使用的咒语就是这样......

db.students.aggregate(
    // Initial document match (uses index, if a suitable one is available)
    { $match: {
        _id : 1
    }},

    // Expand the scores array into a stream of documents
    { $unwind: '$scores' },

    // Filter to 'homework' scores 
    { $match: {
        'scores.type': 'homework'
    }},

    // grab the minimum value score
    { $match: {
        'scores.min.score': 1
    }}
)

我得到的输出就是这个......

{ "result" : [ ], "ok" : 1 }

我做错了什么?

2 个答案:

答案 0 :(得分:0)

你有正确的想法,但在聚合的最后一步你想要做的是按学生分组所有分数并找到$ min值。

将上次管道操作更改为:

{ $group: {
        _id: "$_id",
        minScore: {$min: "$scores.score"}
    }}

答案 1 :(得分:0)

> db.students.aggregate(     
{ $unwind:  "$scores" },`
{ $match:{"scores.type":"homework"} }, 
{ $group: { 
    _id : "$_id", 
   maxScore : { $max : "$scores.score"}, 
   minScore: { $min:"$scores.score"} 
  }
});

how to aggregate on each item in collection in mongoDB