这是一个简单的映射减少 http://www.mongodb.org/display/DOCS/MapReduce这将做你想做的事:
map = function() {
for (var key in this.values){
emit(key, {count:1, trues: (this.values[key] ? 1 : 0)});
}
}
reduce = function(key, values){
var out = values[0];
for (var i=1; i < values.length; i++){
out.count += values[i].count;
out.trues += values[i].trues;
}
return out;
}
finalize = function(key, value){
value.ratio = value.trues / value.count;
return value;
}
db.runCommand({mapReduce:'collection',
map:map,
reduce:reduce,
finalize:finalize,
out:'counts'
})
db.counts.findOne({_id:'alpha'})
{_id: 'alpha', value: {count: 100, trues: 52, ratio: 0.52}}
你也可以做一个upsert http://www.mongodb.org/display/DOCS/Updating当您插入主集合时,就像这样,这将为您提供数据的实时视图:
for (var key in this.values){
db.counts.update({_id:key},
{$inc:{count:1, trues: (this.values[key] ? 1 : 0)}},
true);
}
事实上,您甚至可以结合使用这些方法。执行一次性 MapReduce 批处理作业来填充计数集合,然后使用 upsert 使其保持最新。