如何在MongoDB中打印最小结果

2024-05-21 03:04:44 发布

您现在位置:Python中文网/ 问答频道 /正文

MongoDB noob这里。。。在

所以,我试图打印出一个集合中的最小值得分,看起来像这样。。。在

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

我用的咒语就是这样。。。在

^{pr2}$

我得到的输出是。。。在

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

我做错什么了?在


Tags: nameiddbmongodbtypeprettyfindscore
2条回答
> 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

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

将最后一个管道操作更改为:

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

相关问题 更多 >