MapReduceは、Chien-Weiからの以前の回答によると良いアプローチです。MongoDB 2.2では、AggregationFrameworkの使用を検討することもできます。
たとえば、常に11111と一致している場合は、対象$add
のフィールドの値を指定$match
してから、少なくとも4のフィールドの値のみを一致させることができます。
db.element.aggregate(
// Could use an initial $match here to find candidate documents (using indexed query)
// Use $project to add calculated total
{ $project: {
_id: 0,
element_id: 1,
// Assume we are matching 11111 and field values are always 0 or 1
total: { $add: [ "$field_1", "$field_2", "$field_3", "$field_4", "$field_5" ] }
}},
// Filter to interesting results (at least 4 fields with '1')
{ $match: {
total : { $gte : 4 }
}}
)
サンプル出力:
{ "result" : [ { "element_id" : "b", "total" : 4 } ], "ok" : 1 }
より一般的な比較が必要な場合は$cond
、ターゲット配列と条件付きで照合するために使用できます。例:
var targetArray = [1,1,1,1,1];
db.element.aggregate(
// Could use an initial $match here to find candidate documents (using indexed query)
// Use $project to add calculated total
{ $project: {
_id: 0,
element_id: 1,
total: { $add: [
{ $cond:[{$eq:["$field_1", targetArray[0]]}, 1, 0 ]},
{ $cond:[{$eq:["$field_2", targetArray[1]]}, 1, 0 ]},
{ $cond:[{$eq:["$field_3", targetArray[2]]}, 1, 0 ]},
{ $cond:[{$eq:["$field_4", targetArray[3]]}, 1, 0 ]},
{ $cond:[{$eq:["$field_5", targetArray[4]]}, 1, 0 ]}
]}
}},
// Filter to interesting results (at least 4 fields with a match)
{ $match: {
total : { $gte : 4 }
}}
)
集計オプションと現在の制限の一般的な比較については、関連するStackOverflowの質問:MongoDB集計の比較:group()、$ group、およびMapReduceを参照してください。