根据 Chien-Wei 早期的回答,MapReduce是一种很好的方法。在 MongoDB 2.2 中,您还可以考虑使用聚合框架。
例如,如果您总是匹配 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。