Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to process ISO date sting in the MongoDB mapReduce function in Node.js
    primarykey
    data
    text
    <p>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). </p> <p>It seems that the Date function used inside the mapReduce function is different from normal JS Date function. </p> <ol> <li>How can I use the normal JS Date function inside the map function below?</li> <li>If it is impossible, how to process the ISO date string inside the map function?</li> </ol> <p>.</p> <pre><code>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(); }); } }); </code></pre> <p>=======EDIT: Add the solution=========</p> <p>ISODate solves my issue. The code below works for me.</p> <pre><code>// 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); }; </code></pre> <p>Thanks, Jeffrey</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload