神奇的mongo:mongo JS mapreduce

示例代码:

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
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值