如何在mongoDB中聚合集合中的每个项

2024-04-25 01:10:53 发布

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

MongoDB noob这里。。。在

当我这么做的时候学生数据库().pretty()在shell中,我从我的收藏中得到了一个很长的列表…像这样。。在

{
    "_id" : 19,
    "name" : "Gisela Levin",
    "scores" : [
        {
            "type" : "exam",
            "score" : 44.51211101958831
        },
        {
            "type" : "quiz",
            "score" : 0.6578497966368002
        },
        {
            "type" : "homework",
            "score" : 93.36341655949683
        },
        {
            "type" : "homework",
            "score" : 49.43132782777443
        }
    ]
}

现在我有大约100多个这样的…我需要对每一个运行以下。。。在

^{pr2}$

所以我可以对每个结果进行类似的测试

for item in lowest_hw_score:
    print lowest_hw_score

现在“最低分”只对一个项目有效我要对集合中的所有项目运行此功能…我该怎么做?在


Tags: 项目nameid数据库列表mongodbtypepretty
1条回答
网友
1楼 · 发布于 2024-04-25 01:10:53
> db.students.aggregate(  
{ $match :  { 'scores.type': 'homework' } },
{ $unwind:  "$scores" },
{ $match:{"scores.type":"homework"} }, 
{ $group: { 
    _id : "$_id", 
   maxScore : { $max : "$scores.score"}, 
   minScore: { $min:"$scores.score"} 
  }
});

你不需要第一个$匹配,但是如果“分数.类型“是索引的,这意味着它将在解分之前使用。(我不相信在$undend之后mongo就可以使用这个索引了。)

结果:

^{pr2}$

编辑:在mongoshell中测试和更新

相关问题 更多 >