I'm using the Date function in the mapReduce function in the Node.js application. In the map function below, I convert the ISO date string to the Date object first. Then get the year of the date, which will be used as the key. The expected result is the _id in the output collection is "2013". But in fact, the _id is NaN (The type is Double).
It seems that the Date function used inside the mapReduce function is different from normal JS Date function.
.
var mongodb = require('mongodb');
var map = function() {
var date = new Date("2013-03-19T08:27:58.001Z"); // Convert ISO date string to Date object
var year = date.getFullYear(); // Get the year of the date.
emit(year, this);
};
var reduce = function(key, values) {
if (values.length) {
return values[0];
}
};
/**Connect to MongoDB
*/
var server = new mongodb.Server(dbIP, dbPort, {});
var db = new mongodb.Db(dbName, server, {safe:true});
db.open(function (err, client) {
if( err ) {
console.log('DB: Failed to connect the database');
}
else {
console.log('DB: Database is connected');
db.collection(collectionName).mapReduce(
map,
reduce,
{
out: 'map_reduce_collection'
}
, function (err, collection, stats){
if( err ) {
console.log('Map reduce: Fail.');
}
else {
console.log('Map reduce: Success.');
}
db.close();
});
}
});
=======EDIT: Add the solution=========
ISODate solves my issue. The code below works for me.
// The map and reduce functions are serialized by the driver and run in the MongoDB server.
// The functions used in them should be supported by the mongo shell.
// A tip is checking if a function is supported by map-reduce function by execuing it in the mongo shell.
// For example, the Date function is different from the one supported by Node.js.
// In Node.js, the var date = new Date("2013-03-19T08:27:58.001Z"); works. But it doesn't work in mongo shell.
// So it can't be used in the map function.
var map = function() {
var date = new ISODate("2013-03-19T08:27:58.001Z");
var year = date.getFullYear();
emit(year, this);
};
Thanks, Jeffrey
Post the answer here.
ISODate solves my issue. The code below works for me.
// The map and reduce functions are serialized by the driver and run in the MongoDB server.
// The functions used in them should be supported by the mongo shell.
// A tip is checking if a function is supported by map-reduce function by execuing it in the mongo shell.
// For example, the Date function is different from the one supported by Node.js.
// In Node.js, the var date = new Date("2013-03-19T08:27:58.001Z"); works. But it doesn't work in mongo shell.
// So it can't be used in the map function.
var map = function() {
var date = new ISODate("2013-03-19T08:27:58.001Z");
var year = date.getFullYear();
emit(year, this);
};