conn = new Mongo();
db = conn.getDB("db-name"); //選擇數(shù)據(jù)庫
db.auth("user-name","password"); //用戶驗(yàn)證
var map = function() {
split_result = this.sentence.split(" ");
for (var i in split_result) {
var word = split_result[i].replace(/(^\s*)|(\s*$)/g,"").toLowerCase(); //去除了單詞兩邊可能的空格,并將單詞轉(zhuǎn)換為小寫
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"); //選擇數(shù)據(jù)庫
db.auth("user-name","password"); //用戶驗(yàn)證
var cursor = db.mr_result.find();
while(cursor.hasNext()) {
r = cursor.next();
print(r["_id"] + "\t" + r["value"]);
}
load()函數(shù)用于引入其他文件,這為代碼重用提供了便利。 最簡單的情形是,把數(shù)據(jù)庫連接操作的代碼放在一個(gè)單獨(dú)的文件里,在當(dāng)前目錄建立lib,在lib目錄下創(chuàng)建文件base_operation.js,內(nèi)容如下:
function BaseOperation() {
/*
連接數(shù)據(jù)庫,返回連接對象
*/
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"]);
}