mesh.js - extending MongoDB shell to use moment.js, underscore.js and other useful libraries
mesh.js, which extends MongoDB shell to use famous JavaScript libraries, was convenient so I’ll introduce it.
First, download mesh.js.
curl -O https://raw.githubusercontent.com/skratchdot/mesh/master/mesh.js
Next, load the mesh.js file in MongoDB shell to make it available from the shell. There are two loading patterns.
In the .mongorc.js file, write as follows:
load('/path/to/mesh.js');
You can specify and load the mesh.js file when starting MongoDB shell.
mongo --shell /path/to/mesh.js
Personally, I find writing in .mongorc.js more convenient since I can use it unconsciously.
For example, if you want to check monthly dates from the publication date published_at for product pages in an e-commerce site, you can use it as follows:
> var productPage = db.productpages.findOne( ObjectId( "568f2d5f2e2195f01f663e3d" ) )
> productPage.published_at
ISODate("2016-01-08T04:08:59.822Z")
> var m = moment( productPage.published_at );
> m.toDate()
ISODate("2016-01-08T04:08:59.822Z")
> m.clone().add( 30, 'days' ).toDate()
ISODate("2016-02-07T04:08:59.822Z")
> m.clone().add( 60, 'days' ).toDate()
ISODate("2016-03-08T04:08:59.822Z")
> m.clone().add( 90, 'days' ).toDate()
ISODate("2016-04-07T04:08:59.822Z")
Also, when you want to handle time information in Google Spreadsheet, being able to format it using moment.js’s format method is fantastic.
> m.format('YYYY-MM-DD HH:mm:ss')
2016-01-08 04:08:59
When you want to do date calculations in MongoDB shell, installing mesh.js without hesitation will let you use moment.js and make you happy.
That’s all from the Gemba.