Hi, I’m trying to calculate the number of trips (trip_I) that each route (route_I) has with MapReduce function, but doesn’t work. They also ask me to use a finalize function but I have not been able to figure out how. This is the data:
{ "_id" : ObjectId("602018db89877fd06f61d2f2"), "from_stop_I" : 1908, "to_stop_I" : 1491, "dep_time" : ISODate("2016-09-05T07:40:00.000Z"), "arr_time" : ISODate("2016-09-05T07:41:00.000Z"), "route_type" : 3, "trip_I" : 18, "seq" : 37, "route_I" : 104}
{ "_id" : ObjectId("602018db89877fd06f61d2f3"), "from_stop_I" : 1491, "to_stop_I" : 1500, "dep_time" : ISODate("2016-09-05T07:41:00.000Z"), "arr_time" : ISODate("2016-09-05T07:44:00.000Z"), "route_type" : 3, "trip_I" : 18, "seq" : 38, "route_I" : 104}
{ "_id" : ObjectId("602018dc89877fd06f61d721"), "from_stop_I" : 1156, "to_stop_I" : 1158, "dep_time" : ISODate("2016-09-05T08:06:00.000Z"), "arr_time" : ISODate("2016-09-05T08:06:00.000Z"), "route_type" : 3, "trip_I" : 72, "seq" : 1, "route_I" : 104}
{ "_id" : ObjectId("602018dc89877fd06f61d722"), "from_stop_I" : 1158, "to_stop_I" : 1160, "dep_time" : ISODate("2016-09-05T08:06:00.000Z"), "arr_time" : ISODate("2016-09-05T08:07:00.000Z"), "route_type" : 3, "trip_I" : 72, "seq" : 2, "route_I" : 104}
{ "_id" : ObjectId("602018dc89877fd06f61d746"), "from_stop_I" : 1491, "to_stop_I" : 1500, "dep_time" : ISODate("2016-09-05T08:27:00.000Z"), "arr_time" : ISODate("2016-09-05T08:30:00.000Z"), "route_type" : 3, "trip_I" : 72, "seq" : 38, "route_I" : 104}
{ "_id" : ObjectId("6020193c89877fd06f639dec"), "from_stop_I" : 1156, "to_stop_I" : 1158, "dep_time" : ISODate("2016-09-05T23:20:00.000Z"), "arr_time" : ISODate("2016-09-05T23:20:00.000Z"), "route_type" : 3, "trip_I" : 6972, "seq" : 1, "route_I" : 104}
{ "_id" : ObjectId("6020193c89877fd06f639ded"), "from_stop_I" : 1158, "to_stop_I" : 1160, "dep_time" : ISODate("2016-09-05T23:20:00.000Z"), "arr_time" : ISODate("2016-09-05T23:21:00.000Z"), "route_type" : 3, "trip_I" : 6972, "seq" : 2, "route_I" : 104}
{ "_id" : ObjectId("6020193c89877fd06f639dee"), "from_stop_I" : 1160, "to_stop_I" : 1162, "dep_time" : ISODate("2016-09-05T23:21:00.000Z"), "arr_time" : ISODate("2016-09-05T23:21:00.000Z"), "route_type" : 3, "trip_I" : 6972, "seq" : 3, "route_I" : 104}
This is the code:
function mapFunction () {
var key = this.route_I;
var value = { totalTrips: this.trip_I,totalRegistros:1 };
emit( key, value );
};
function reduceFunction (key, trips) {
var reducedObject = { totalTrips: 0,totalRegistros:0 };
trips.forEach(function(value) {
reducedObject.totalTrips ++;
reducedObject.totalRegistros += value.totalRegistros;
})
;
return reducedObject;
};
function finalizeFunction(key, reducedObject) {
//???
return reducedObject;
};
db.routes.mapReduce(
mapFunction,
reduceFunction,
{
out: "routes_out",
finalize: finalizeFunction
}
)
The output should be 3 trips for route 104. Thanks