问题
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