示例代码:
function print_collection(db, name)
{
var res = db[name].find()
res.forEach(function(doc){
printjson(doc)
})
}
function prepare_data(db)
{
data = [
{price:1, name:"Simplify Your Life"},
{price:1, name:"Getting Things Done"},
{price:1, name:"The War of Art"},
{price:2, name:"Jane Eyre"},
{price:2, name:"War and Peace"},
{price:3, name:"Hong Lou Meng"},
{price:3, name:"Xi You Ji"},
{price:3, name:"Sango Yanyi"}
]
data.forEach(function(doc){
db.book.insert(doc)
})
}
/*
Count the books of the same price, but not the books with price 1.
*/
function map_fn()
{
emit(this.price.toString(), {name:this.name})
}
function reduce_fn(key, values)
{
var sum = 0;
values.forEach(function(doc){
sum += 1;
})
return sum
}
function finalize_fn(key, value)
{
return "newbook:" + value.toString()
}
function test()
{
var db = connect("liyong11_search_test")
db.book.remove()
prepare_data(db)
res = db.runCommand(
{
mapreduce:"book",
map:map_fn,
reduce:reduce_fn,
out:"result_collection_name",
finalize:finalize_fn,
query:{price:{"$ne":1}}
})
printjson(res)
print_collection(db, "result_collection_name")
}
test()
map的参数为this,每个this代表表中的一条记录。map后的中间结果:
[
{
"_id": 2,
"values": [
"Jane Eyre",
"War and Peace"
]
},
{
"_id": 3,
"values": [
"Hong Lou Meng",
"Xi You Ji",
"Sango Yanyi"
]
}
]
reduce的输入为上次中间结果的一个数组项,reduce返回结果保存在value中。reduce将values转为value,处理后结果如下。
{ "_id" : "2", "value" : "newbook:2" }
{ "_id" : "3", "value" : "newbook:3" }
这些结果被保存到 out 指定的collection中。
runCommand的结果记录了一些可能有用的信息:
{
"result" : "result_collection_name",
"timeMillis" : 22,
"counts" : {
"input" : 5,
"emit" : 5,
"reduce" : 2,
"output" : 2
},
"ok" : 1
}