conn = new Mongo();
db = conn.getDB("db-name"); //选择数据库
db.auth("user-name","password"); //用户验证
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) {
print(key+":"+Array.sum(values));
return Array.sum(values);
}
db.data.mapReduce(
map,
reduce,
{out:{merge:"mr_result"}}
)
conn = new Mongo();
db = conn.getDB("db-name"); //选择数据库
db.auth("user-name","password"); //用户验证
var cursor = db.mr_result.find();
while(cursor.hasNext()) {
r = cursor.next();
print(r["_id"] + "\t" + r["value"]);
}
load()函数用于引入其他文件,这为代码重用提供了便利。 最简单的情形是,把数据库连接操作的代码放在一个单独的文件里,在当前目录建立lib,在lib目录下创建文件base_operation.js,内容如下:
function BaseOperation() {
/*
连接数据库,返回连接对象
*/
this.getDB = function() {
conn = new Mongo();
db = conn.getDB("db-name");
db.auth("user-name","password");
return db;
}
}
load("lib/base_operation.js");
BO = new BaseOperation();
db = BO.getDB();
var cursor = db.mr_result.find();
while(cursor.hasNext()) {
r = cursor.next();
print(r["_id"] + "\t" + r["value"]);
}