Mongo MapReduce select latest date

荒凉一梦 提交于 2019-12-12 09:41:24

问题


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
        }   
    ); 

}

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?


回答1:


Have you considered using either of the following approaches?

Find the MAX timeStampField in the collection:

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

OR:

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; 
                  }
              }
  }
);


来源:https://stackoverflow.com/questions/12785550/mongo-mapreduce-select-latest-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!