MapReduce可能是一个很好的 Select ,它可以在服务器上处理文档,而无需在客户机上进行操作(因为DB服务器上没有拆分字符串的功能(open issue).
从map
函数开始.在下面的示例中(可能需要更健壮),每个文档都会传递给map
函数(as this
).代码查找summary
字段,如果有,则将其小写,在空格上拆分,然后为找到的每个单词发送1
.
var map = function() {
var summary = this.summary;
if (summary) {
// quick lowercase to normalize per your requirements
summary = summary.toLowerCase().split(" ");
for (var i = summary.length - 1; i >= 0; i--) {
// might want to remove punctuation, etc. here
if (summary[i]) { // make sure there's something
emit(summary[i], 1); // store a 1 for each word
}
}
}
};
然后,在reduce
函数中,它对map
函数找到的所有结果求和,并为上面列出的每个单词返回一个离散的总数.
var reduce = function( key, values ) {
var count = 0;
values.forEach(function(v) {
count +=v;
});
return count;
}
最后,执行mapReduce:
> db.so.mapReduce(map, reduce, {out: "word_count"})
结果和您的样本数据:
> db.word_count.find().sort({value:-1})
{ "_id" : "is", "value" : 3 }
{ "_id" : "bad", "value" : 2 }
{ "_id" : "good", "value" : 2 }
{ "_id" : "this", "value" : 2 }
{ "_id" : "neither", "value" : 1 }
{ "_id" : "or", "value" : 1 }
{ "_id" : "something", "value" : 1 }
{ "_id" : "that", "value" : 1 }