Mongo MapReduce select last date

I cannot get my MapReduce reduction function to work correctly. 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 reduction 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 get the last date of a grouped object. What am I doing wrong?

+4
source share
1 answer

Have you considered using one 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 MAX timeStampField , for user_id in the collection (if the DB is not plastered):

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

Source: https://habr.com/ru/post/1438454/


All Articles