元の例には、おそらく期待どおりの動作をしていない構文があります。つまり、特定のタイプのスコアのみを一致させることが目的のようです(例では「exam」、説明では「quiz」) 。
以下は、MongoDB2.2シェルを使用したいくつかの例です。
$elemMatch
投影
$elemMatchプロジェクション を使用できます 配列内の最初に一致する要素を返すには:
db.students.find(
// Search criteria
{ '_id': 22 },
// Projection
{ _id: 0, scores: { $elemMatch: { type: 'exam' } }}
)
結果は、各ドキュメントの配列の一致する要素になります。例:
{ "scores" : [ { "type" : "exam", "score" : 75.04996547553947 } ] }
集約フレームワーク
完全に一致する配列要素を返す代わりに、複数の一致する値を表示したり、結果ドキュメントの形状を変更したりする場合は、アグリゲーションフレームワーク :
db.students.aggregate(
// Initial document match (uses index, if a suitable one is available)
{ $match: {
'_id': 22, 'scores.type' : 'exam'
}},
// Convert embedded array into stream of documents
{ $unwind: '$scores' },
// Only match scores of interest from the subarray
{ $match: {
'scores.type' : 'exam'
}},
// Note: Could add a `$group` by _id here if multiple matches are expected
// Final projection: exclude fields with 0, include fields with 1
{ $project: {
_id: 0,
score: "$scores.score"
}}
)
この場合の結果は次のようになります。
{ "result" : [ { "score" : 75.04996547553947 } ], "ok" : 1 }