• (15)mongodb mapReduce的概念及用法


      mapReduce从功能上说类似于RDBMS中的group,它的强大之处在于很好的支持分布式。相比于group、aggregate,mapReduce的用法很简单,其实它的工作原理也很简单,下面介绍一下。

      mapReduce工作分为两步,一是映射,即map,将数据按照某一个规则映射到一个数组里,比如按照type或者name映射,同一个type或者name的数据形成一个数组,二是规约,即reduce,它接收映射规则和数组,然后计算。举例如下:

      1、计算每个栏目的库存总量

      var map=function(){
        emit(this.cat_id,this.goods_number);
      }

      var reduce=function(cat_id,numbers){
        return Array.sum(numbers);
      }

      db.goods.mapReduce(map,reduce,{out:'res'});

      将相同cat_id的goods_number分别映射到各自的数组中;对每一个数组进行求和,执行结果会生成一个res表,该表中保存了执行的结果,如下:

      > db.res.find();
      { "_id" : 2, "value" : 0 }
      { "_id" : 3, "value" : 203 }
      { "_id" : 4, "value" : 3 }
      { "_id" : 5, "value" : 8 }
      { "_id" : 8, "value" : 61 }

    2、计算每个栏目下商品的平均价格

      var map=function(){
        emit(this.cat_id,this.shop_price);
      }
      var reduce=function(cat_id,values){
        return Array.avg(values);
      }
      db.goods.mapReduce(map,reduce,{out:'res'});

      执行结果如下:

      > db.res.find();
      { "_id" : 2, "value" : 823.33 }
      { "_id" : 3, "value" : 1746.0666666666666 }
      { "_id" : 4, "value" : 2297 }
      { "_id" : 5, "value" : 3700 }
      { "_id" : 8, "value" : 75.33333333333333 }
      { "_id" : 11, "value" : 31 }
      { "_id" : 13, "value" : 33.5 }
      { "_id" : 14, "value" : 54 }
      { "_id" : 15, "value" : 70 }

    3、计算每个栏目下商品的平均价格,只统计价格大于100的

      var map=function(){
        emit(this.cat_id,this.shop_price);
      }
      var reduce=function(cat_id,values){
        return Array.avg(values);
      }

      db.goods.mapReduce(map,reduce,{query:{shop_price:{$gt:100}},out:'res'});

      执行结果如下:

      > db.res.find();
      { "_id" : 2, "value" : 823.33 }
      { "_id" : 3, "value" : 1746.0666666666666 }
      { "_id" : 4, "value" : 2297 }
      { "_id" : 5, "value" : 3700 }

    备注:

      Array中的常用方法有如下几种:

      contains、unique、shuffle、tojson、fetchRefs、sum、avg、stdDev,

      可以通过下面的方式查看:for(var key in Array){ print(key); }

      

  • 相关阅读:
    5M1E,软件质量管理最佳解决方案
    Laravel 刚创建的项目 API 无法使用 Session,是没有在Api的请求内开启Session
    python添加默认模块搜索路径
    [传纸条]
    [miller_rabin]
    国内rog游戏手机2与国际版本的 差别
    windows下依端口查进程
    gor phone 2 优缺点
    IDA pro 6.8 导入cpu解析模块报错 ImportError: No module named ida_ bytes
    JEB 4.5 新增 RISC-V 反编译器支持
  • 原文地址:https://www.cnblogs.com/javasl/p/11333506.html
Copyright © 2020-2023  润新知