我有以下 map 和 reduce 函数,它们应该给我一个组的最大日期。
地图:
function () {
if (this.topic_id != 0) {
emit(this.topic_id, {date_posted : this.date_posted});
}
}
减少:
function (key, values) {
var re_date = ISODate('1970-01-01T00:00:00Z');
values.forEach(function (value) {
if (re_date == ISODate('1970-01-01T00:00:00Z')) {
re_date = value.date_posted;
}
if (re_date < value.date_posted) {
re_date = value.date_posted;
}
});
return {date_posted: re_date};
}
目前,它给出以下输出:
{ "_id" : "1", "value" : ISODate("2010-06-01T13:36:30Z") }
{ "_id" : "10", "value" : { "date_posted" : ISODate("2010-05-19T21:33:16Z") } }
{ "_id" : "1000", "value" : { "date_posted" : ISODate("2010-07-04T04:09:43Z") } }
{ "_id" : "1004", "value" : ISODate("2010-07-05T01:27:53Z") }
{ "_id" : "1007", "value" : { "date_posted" : ISODate("2010-07-04T23:44:56Z") } }
{ "_id" : "1009", "value" : ISODate("2010-08-12T19:05:35Z") }
{ "_id" : "1012", "value" : ISODate("2010-08-14T19:56:35Z") }
{ "_id" : "1014", "value" : { "date_posted" : ISODate("2010-07-05T07:18:56Z") } }
{ "_id" : "1022", "value" : ISODate("2010-07-06T21:17:57Z") }
{ "_id" : "1024", "value" : { "date_posted" : ISODate("2010-07-06T12:37:28Z") } }
{ "_id" : "1028", "value" : ISODate("2010-07-08T00:24:59Z") }
{ "_id" : "1029", "value" : ISODate("2010-07-26T12:08:34Z") }
{ "_id" : "1042", "value" : { "date_posted" : ISODate("2010-10-01T19:22:29Z") } }
{ "_id" : "1043", "value" : { "date_posted" : ISODate("2010-07-20T01:38:44Z") } }
{ "_id" : "1048", "value" : { "date_posted" : ISODate("2010-07-08T19:29:14Z") } }
{ "_id" : "1049", "value" : ISODate("2010-07-08T11:07:30Z") }
{ "_id" : "105", "value" : ISODate("2010-05-21T01:53:20Z") }
{ "_id" : "1053", "value" : { "date_posted" : ISODate("2010-07-08T17:53:57Z") } }
{ "_id" : "1056", "value" : { "date_posted" : ISODate("2010-07-08T22:35:02Z") } }
{ "_id" : "1060", "value" : { "date_posted" : ISODate("2010-07-09T06:33:57Z") } }
我期待每一行的值字段总是有“date_posted”元素,但显然只有一些有这个。我的地图功能有误吗?
原始数据样本:
db.posts.find({"topic_id" : {$in : ["105", "1053", "1000", "1004", "1007"]}}, {"date_posted" : 1, "topic_id" : 1})
{ "_id" : "1010", "date_posted" : ISODate("2010-07-05T01:27:53Z"), "topic_id" : "1004" }
{ "_id" : "106", "date_posted" : ISODate("2010-05-21T01:52:59Z"), "topic_id" : "105" }
{ "_id" : "107", "date_posted" : ISODate("2010-05-21T01:53:20Z"), "topic_id" : "105" }
{ "_id" : "1001", "date_posted" : ISODate("2010-07-04T04:09:43Z"), "topic_id" : "1000" }
{ "_id" : "1006", "date_posted" : ISODate("2010-07-04T23:21:30Z"), "topic_id" : "1004" }
{ "_id" : "1008", "date_posted" : ISODate("2010-07-04T23:44:56Z"), "topic_id" : "1007" }
{ "_id" : "1054", "date_posted" : ISODate("2010-07-08T17:53:57Z"), "topic_id" : "1053" }