Mongo MapReduce选择最新日期 [英] Mongo MapReduce select latest date

查看:79
本文介绍了Mongo MapReduce选择最新日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法让我的MapReduce reduce函数正常工作.这是我的地图功能:

I can't seem to get my MapReduce reduce function to work properly. Here is my map function:

function Map() {
    day = Date.UTC(this.TimeStamp.getFullYear(), this.TimeStamp.getMonth(),this.TimeStamp.getDate());   

    emit(
        {
            search_dt: new Date(day),
            user_id: this.UserId
        },                  
        {
            timestamp: this.TimeStamp
        }   
    ); 

}

这是我的reduce函数:

And here is my reduce function:

function Reduce(key, values) {

    var result = [timestamp:0];

    values.forEach(function(value){
        if (!value.timestamp)
            continue;
        if (result.timestamp < value.timestamp)
            result.timestamp = value.timestamp; 
    }); 
    return result;

}

我想检索分组对象的最新日期.我在做什么错了?

I want to retrieve the latest date of the grouped object. What am I doing wrong?

推荐答案

您是否考虑过使用以下两种方法之一?

Have you considered using either of the following approaches?

在集合中找到MAX timeStampField :

Find the MAX timeStampField in the collection:

db.collectionName.ensureIndex( { "timeStampField": -1 } );
db.collectionName.find({},{"timeStampField":1}).sort({timeStampField:-1}).limit(1);

OR:

在集合中的每个 user_id 中查找MAX timeStampField (如果数据库未分片):

Find the MAX timeStampField, per user_id in the collection (if DB not sharded):

db.collectionName.group(
  {  key: { "user_id" : 1 }
   , initial: { maxTimeStamp   : new Timestamp()  }
   , cond:    { timeStampField : {$exists : true}, timeStampField : {$gt: new Timestamp()} }
   , reduce:  function(doc,out) { 
                  if (out.maxTimeStamp < doc.timeStampField) { 
                      out.maxTimeStamp = doc.timeStampField; 
                  }
              }
  }
);

这篇关于Mongo MapReduce选择最新日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆