Mongo MapReduce select latest date

2019-05-05 11:25发布

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条回答
太酷不给撩
2楼-- · 2019-05-05 11:57

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; 
                  }
              }
  }
);
查看更多
登录 后发表回答