【问题标题】:Map reduce code for group by with having clause and where conditions通过具有子句和 where 条件映射减少分组的代码
【发布时间】:2012-08-18 21:01:03
【问题描述】:

我有一个用户集合如下

{
    "id":"id here", 
    name: 'name here', 
    height: 'height here', 
    weight: 'weight here', 
    lastLogin:[array of login dates], 
    messagesSentOn: [array of messages sent date]
}

我需要找到所有上个月登录但不止一次的用户,以及上个月发送超过 25 条消息且体重超过 50 且身高超过 5 英寸的用户。对于上述情况,如何在 mongodb 中编写 map reduce 函数?

【问题讨论】:

    标签: php mongodb map reduce


    【解决方案1】:

    我在 shell 中提供了一个示例。我不确定 MR 是解决这个问题的最佳解决方案,我鼓励您考虑替代解决方案以避免单线程 Javascript。例如,您可以存储一个仅包含当月登录信息或消息的附加字段。每次添加登录名和/或消息时,都会增加一个计数器字段。此架构将允许您在没有聚合命令的情况下找到匹配的文档。

    您还应该研究新的聚合框架,它将在 MongoDB 版本 2.2(即将推出)中提供:http://docs.mongodb.org/manual/applications/aggregation/

    最后一点 - 为了提高性能,您应该确保在 MR 命令中包含一个查询以清除不匹配的文档(参见下面的示例)。

    输入文件:

    { "_id" : 1, "name" : "Jenna", "height" : 100, "weight" : 51, "lastLogin" : [ 1, 2, 3, 4 ], "messageSentOn" : [ 4, 5, 5, 7 ] }
    { "_id" : 2, "name" : "Jim", "height" : 60, "weight" : 49, "lastLogin" : [ 2, 4 ], "messageSentOn" : [ 5, 6 ] }
    { "_id" : 3, "name" : "Jane", "height" : 90, "weight" : 60, "lastLogin" : [ 1 ], "messageSentOn" : [ 3, 6 ] }
    { "_id" : 4, "name" : "Joe", "height" : 70, "weight" : 65, "lastLogin" : [ 5, 6, 7 ], "messageSentOn" : [ 3, 6, 7 ] }
    

    MR 函数:

    map = function(){ 
       var monthLogins = 0; 
       var monthMessages = 0; 
       var monthDate = 2;  
       for(var i=0; i<this.lastLogin.length; i++){     
           if(this.lastLogin[i] > monthDate){         
                monthLogins++; 
           } 
       } 
       for(var i=0; i<this.messageSentOn.length; i++){     
          if(this.messageSentOn[i] > monthDate){         
             monthMessages++; 
          } 
       } 
       if(monthLogins > 1 && monthMessages > 2)
          { emit(this._id, null); 
       } 
    }
    
    reduce = function (key, values) {
       //won't be called because a single document is emitted for each key
    }
    

    MR 命令:

    db.collection.mapReduce(map, reduce, {query: {weight: {$gt : 50}, height: {$gt: 5}, lastLogin: {$gt: 2}}, out: {inline:1}})
    

    输出:

    {"_id" : 1, "value" : null},
    {"_id" : 4, "value" : null}
    

    【讨论】:

      猜你喜欢
      • 2021-09-13
      • 2018-01-26
      • 2020-05-11
      • 1970-01-01
      • 2018-11-08
      • 2014-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多