2014-03-23
作为一个数据库,MongoDB有一个很大的优势——它使用js管理数据库,所以也能够使用js脚本进行复杂的管理——这种方法非常灵活。
笔者使用的mongodb版本为2.4.7。
入门
前面的文章 MapReduce in MongoDB 中,mapreduce示例在js脚本中可以写成下面的方式(略作修改):
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"}}
)
保存为test01.js
,在终端中运行:
$ mongo test01.js
运行结束后可以在集合mr_result
中查看mapreduce结果。
值得注意的是,在js脚本中如果直接:
db.mr_result.find();
是无法输出结果的。
应该使用下面的方式输出结果:
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"]);
}
保存为test02.js
,运行:
$ mongo test02.js
结果如下:
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()函数
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;
}
}
在当前目录下建立文件test03.js
,内容如下:
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"]);
}
运行test03.js
的效果和test02.js
相同。
更多
更多内容请参考资料[1][2][3][4]。
资料
[1] Write Scripts for the mongo Shell
[2] MongoDB Scripting
[3] Getting Started with the mongo Shell
[4] load()