注:作者使用的mongodb版本為2.4.7。
入門例子
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"}}
)
保存為test01.js,在終端中運(yùn)行:
運(yùn)行結(jié)束后可以在集合mr_result中查看mapreduce結(jié)果。
值得注意的是,在js腳本中如果直接:
是無法輸出結(jié)果的。
應(yīng)該使用下面的方式輸出結(jié)果:
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"]);
}
保存為test02.js,運(yùn)行:
結(jié)果如下:
a 1
code 1
collection 1
consider 1
contains 1
documents 1
error 1
follow 1
following 3
found 1
get 1
i 2
in 1
link 1
map-reduce 1
of 1
on 1
operations 1
orders 1
prototype 1
that 1
the 4
this 1
when 1
使用load()函數(shù)
load()函數(shù)用于引入其他文件,這為代碼重用提供了便利。 最簡單的情形是,把數(shù)據(jù)庫連接操作的代碼放在一個單獨(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;
}
}
在當(dāng)前目錄下建立文件test03.js,內(nèi)容如下:
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"]);
}
運(yùn)行test03.js的效果和test02.js相同。