作为一个优秀的编程模型,MapReduce在大数据处理中有很大的优势,而mongodb也支持这一编程模型,本文通过简单的单词计数示例论述在mongodb中如何使用MapReduce
注:作者使用的MongoDB为2.4.7版本。
单词计数示例:
插入用于单词计数的数据:
复制代码 代码如下:
db.data.insert({sentence:'Consider the following map-reduce operations on a collection orders that contains documents of the following prototype'})
db.data.insert({sentence:'I get the following error when I follow the code found in this link'})
图个简洁,数据中没有包含标点符号。 在mongo shell写入以下内容:
复制代码 代码如下:
var map = function() {
split_result = this.sentence.split(" ");
for (var i in split_result) {
var word = split_result[i].replace(/(^\s*)|(\s*$)/g,"").toLowerCase(); //去除了单词两边可能的空格,并将单词转换为小写
if (word.length != 0) {
emit(word, 1);
}
}
}
var reduce = function(key, values) {
return Array.sum(values);
}
db.data.mapReduce(
map,
reduce,
{out:{inline:1}}
)
以上就是MongoDB中MapReduce编程模型使用实例的详细内容,更多请关注0133技术站其它相关文章!