2012-11-20 30 views
0

的MongoDB这里小白......如何,在每个项目聚集在收集MongoDB中

当我做db.students.find()。漂亮的()在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 ...我需要运行在他们每个人的以下...

lowest_hw_score = 

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

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

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

    // Sort in descending order 
    { $sort: { 
     'scores.score': 1 
    }}, 

    { $limit: 1} 
) 

所以我可以运行的东西像这样对每个结果

for item in lowest_hw_score: 
    print lowest_hw_score 

现在“lowest_score”只适用于一个项目我在集合中的所有项目上运行此项目......我该如何执行此操作?

+0

你得分最低的后由学生? (作业) – sambomartin

+0

你刚才在这里问同样的问题,不是吗? http://stackoverflow.com/questions/13464232/how-to-print-minimum-result-in-mongodb –

回答

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

你并不真正需要的第一$比赛,但如果“scores.type”被索引,这意味着它会解开得分之前使用。 (我不相信以后$开卷蒙戈将能够使用索引。)

结果:

{ 
"result" : [ 
    { 
     "_id" : 19, 
     "maxScore" : 93.36341655949683, 
     "minScore" : 49.43132782777443 
    } 
], 
"ok" : 1 
} 

编辑:测试和蒙戈更新的外壳

+0

当我从python文件里面运行这个时,我得到这个... – thefonso

+0

看不到你在做什么让我知道如果你仍然有问题 - 我会尽快为你测试 – sambomartin

+0

@thefonso - 更新的答案,在shell中测试 – sambomartin