Writing administrative scripts for MongoDB is a relatively simple task (if you know JavaScript).

Scripts are written in plain old JS and can be run via mongo <database> <path-to-file.js>

Since version 2.4, MongoDB uses the V8 JavaScript engine.

The same engine used in Google Chrome browser and the popular Node.js platform. Read more here.

This makes the prospect of running the same code client, server and database side much more appealing (Less differences between targets).

What’s also interesting is the potential to utilize modules from NPM to make your work easier.

For example, let’s say we want to do some testing and need to generate fake user data.

Sure, we could write some code in our application environment to do this, but why ignore the mongo shell?

On npm, I came across a library called chance. It describes itself as a ‘random generator helper for JavaScript’.

Sounds good, let’s put it to work.

While in a mongo shell we can load arbitrary script files via the load method.

We won’t be using this however; instead we are going to take advantage of browserify and it’s powerful bundling features.

Additionally we will use the babelify transform so we can use ES6/ES2015 syntax.

While browserify is targeted at Web browsers, I have not come across anything in the code it generates that prevents our intended use (yet).

The script below will insert 1000 users with their information randomized:


import Chance from 'chance';

var chance = new Chance();

for (var i = 0; i < 1000; i++) {

    db.users.insert({
        name: chance.name(),
        email: chance.email(),
        comments: ((n) => {

          var list = [];

          for(var c=0; c<n; c++)
          list.push({
                    content: chance.sentence(),
                    created_at: new Date(chance.hammertime())
                });
  return list;

        })(chance.integer({
            min: 0,
            max: 10
        }))
    });

}

To bundle this script:

browserify -t babelify script.js > build.js

Now we have a build.js file that we can pass to mongo on the command line via:

mongo mydatabase build.js

Let’s check the database:

Shell Output

I see real potential for productivity here, particularly in being able to share admin scripts via npm.

As to be expected however, there are caveats:

For one thing, the mongo shell treats numbers as floating point by default. You have to cast using NumberInt() or NumberLong to get 32bit or 64bit intergers respectively.

This could lead to some subtle bugs particularly in libraries where number formats matter. More on shell data types here.

Generally, testing should be done before you use any library on production data. Obviously one should not expect to open a Web socket or make HTTP requests from the shell.

At least not up to version 3. :)