【问题标题】:Pymongo MapReduce as sum of subarray elementPymongo MapReduce 作为子数组元素的总和
【发布时间】:2018-01-28 05:07:16
【问题描述】:

我正在尝试对这种数据集执行 MapReduce:

 {
"_id": "599861ce7ce78cd973746906",
"name": "Macias Rosario",
"col": [
  {
    "date": "15/03/2016",
    "name": "MAGNEATO",
    "amount": 313.86
  },
  {
    "date": "08/08/2016",
    "name": "FORTEAN",
    "amount": 151.06
  },
  {
    "date": "05/11/2014",
    "name": "ECRATIC",
    "amount": 291.68
  }
]

}

目标是总结姓名 Macias Rosario 的所有 金额。目前我用我的代码以这种方式按子元素this.col.name 进行分组:

mapper = Code("""
                           function() {   
                           for (var index = 0; index < this.col.length; ++index) {
                                var col = this.col[index];
                                emit(col.name, col.amount );
                            }   
                           }
                           """)
        reducer = Code("""
                           function(key, values) {
                               var total =  0;
                               for( var i = 0; i < values.length; ++i){
                                    total += values[i];


                               }
                               return value.price;
                           }
               """)
        result = collection.map_reduce(mapper, reducer, "myresult")

有没有人知道如何参考,或按this.name 分组,而不是this.col.name,因为我不知道了,而且我快疯了? PS不建议我使用aggregate,这样做了,也想尝试这种方式:) 亲切的问候,

【问题讨论】:

    标签: javascript python mongodb mapreduce pymongo


    【解决方案1】:

    我希望下面的代码有帮助(也适用于 pymongo)

    这是我的地图功能:

    var mapFunction = function() {
        for (var idx = 0; idx < this.col.length; idx++) {
            var key = this.name;
            var value = { amount : this.col[idx].amount };
            emit(key, value);
       } 
    };
    

    以下是我的reduce函数:

    var reduceFunction = function(key, amountVl) {
        reduceVal = { amount : 0 };
        for (var idx = 0; idx < amountVl.length; idx++) {
            reduceVal.amount += amountVl[idx].amount; 
        }
        return reduceVal;
    }
    

    使用您的示例数据生成:

    { "_id" : "Macias Rosario", "value" : { "amount" : 756.6 } }
    

    【讨论】:

      猜你喜欢
      • 2012-09-11
      • 2017-07-02
      • 2019-01-03
      • 1970-01-01
      • 2015-09-20
      • 2015-10-06
      • 1970-01-01
      • 1970-01-01
      • 2017-12-06
      相关资源
      最近更新 更多