0

ここにMongoDB初心者...

シェルで db.students.find().pretty() を実行すると、コレクションから長いリストが取得されます...そのように..

{
    "_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」はコレクション内のすべてのアイテムでこれを実行するには、1 つのアイテムでのみ機能します...どうすればよいですか?

4

1 に答える 1

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"} 
  }
});

最初の $match は実際には必要ありませんが、「scores.type」がインデックス化されている場合は、スコアを巻き戻す前に使用されることを意味します。($unwind mongo がインデックスを使用できるようになるとは思えません。)

結果:

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

編集:mongoシェルでテストおよび更新

于 2012-11-20T01:28:32.597 に答える