zoukankan      html  css  js  c++  java
  • mongodb(map-reduce)

    下例中给出mongoose的一个mapreduce例子,参考mongoose官网。

    基本概念:

    Map函数
    接受一个键值对(key-value pair),产生一组中间键值对。MapReduce框架会将map函数产生的中间键值对里键相同的值传递给一个reduce函数。
    Reduce函数
    接受一个键,以及相关的一组值,将这组值进行合并产生一组规模更小的值(通常只有一个或零个值)。
     
    • 定义一个collection:
    var user    = new Schema({    
        username:{type:String}, 
        
        password:{type:String},
    })
    • mapreduce:
    exports.test = function(){    
        var user = require('../dao/user');
        var model = user.model;
        
        var option = {};
        //输出为_id:name, value:1
        option.map = function () { emit(this.username, 1) }
        //将键值相同的传给同一个reduce函数,此时k为_id:name, vals 为value的数组
        //当不存在多个键值对时,该reduce函数不会被调用
        option.reduce = function (k, vals) {
            return vals.length}
        model.mapReduce(o, function (err, results) {
          console.log(results)
        });
    }
    • 输出结果:
    //数据库中存有三条记录,一条用户名为hello,两条用户名为test
    [ { _id: 'hello', value: 1 }, { _id: 'test', value: 2 } ]
  • 相关阅读:
    Vue 路由的编程式导航与history模式
    Vue 路由配置、动态路由
    Vue 组件传值
    Vue 组件以及生命周期函数
    Vue 封装js
    记一次proc_open没有开启心得感悟
    面向内容的标记语言--markdonw
    浅谈索引
    mysql主从配置
    centos7下操作防火墙
  • 原文地址:https://www.cnblogs.com/Fredric-2013/p/4445396.html
Copyright © 2011-2022 走看看