How to Pass Arguments from Mongo Command Line to Javascript

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

You can execute javascript files from mongo but it’s not intuitive to pass parameters to them. +++ This is the issue we’ll tackle. You might have a javascript that prints your default database stats but what if you wanted to pass it a variable to which database you wanted to print stats for instead of having it hardcoded.

Prerequisites

  • You should have MongoDB installed and running.
  • It’s recommended that you create a database and collection to experiment with as you follow along.
  • Some command line experience is recommended.
  • Some javaScript is recommended.

Goal

We always like to start out with an explicit goal to make sure we hit our mark by the end of the tutorial. To demonstrate passing arguments to a javascript file, our goal is to pass the name of a database to a script (js) that will print that database stats to the MongoDB console.

We won’t be starting from scratch for this tutorial. We have a javascript file dbStats.js that outputs the stats of a database. The database name is hardcoded into the script. Our goal is to change this file and how we run it so that it can accept any database and print out the stats for that database.

Let’s take a look at the script as it exists currently:

File: dbStats.js

1
2
3
4
5
print("Running dbStats.js");

conn = new Mongo();
db = conn.getDB("demoDatabase");
db.stats();

Here’s how we would execute that script from the MongoDB shell:

1
$ mongo < dbStats.js

Here’s the results that print out from the console when our script is run:

1
2
3
4
5
6
MongoDB shell version v4.0.3
connecting to: mongodb://127.0.0.1:27017
Implicit session: session { "id" : UUID("026518c1-8c8b-424d-a11a-67a55a3b70ef") }
MongoDB server version: 4.0.3
Running dbStats.js
bye

1. Modify the javascript file to accept a variable database name

Our first step is to move away from the hardcoded database name ( db = conn.getDB("demoDatabase"); ) and allow the script to instead use a variable as the database name. We do this by replacing that line of code with:

1
db = conn.getDB(databaseName);

Right now the variable databaseName is not defined but we will pass this variable in later.

We also need a printjson() method around db.stats because otherwise it gets silenced with the –eval flag that we use later. Let’s take a look at the updated file:

File: dbStats.js `js print(“Running dbStats.js”);

conn = new Mongo(); db = conn.getDB(databaseName); printjson(db.stats()); `

2. Pass a Variable to the File using eval()

The MongoDB shell is capable of executing Javascript fragments by using the --eval option. We’ll take advantage of this by declaring the databaseName variable we need to pass into our file. So from the MongoDB shell we delcare databaseName as demoDatabase like this:

1
$ mongo --eval 'var databaseName="demoDatabase"' dbStats.js

This variable is then used in dbStats.js to output that database’s stats which gives results:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
$ mongo --eval 'var databaseName="demoDatabase"' dbStats.js
MongoDB shell version v4.0.3
connecting to: mongodb://127.0.0.1:27017
Implicit session: session { "id" : UUID("d77fff63-b871-4745-8919-c508674283cd") }
MongoDB server version: 4.0.3
Running dbStats.js
{
        "db" : "demoDatabase",
        "collections" : 5,
        "views" : 0,
        "objects" : 22,
        "avgObjSize" : 76.36363636363636,
        "dataSize" : 1680,
        "storageSize" : 143360,
        "numExtents" : 0,
        "indexes" : 5,
        "indexSize" : 126976,
        "fsUsedSize" : 114071158784,
        "fsTotalSize" : 499963174912,
        "ok" : 1
}

Now can pass in any database to our script using commands like below:

1
2
$ mongo --eval 'var databaseName="database1"' dbStats.js
$ mongo --eval 'var databaseName="database2"' dbStats.js

Conclusion

We showed you how to pass variables through the MongoDB shell to a Javascript file. The MongoDB shell is built in Javascript so this type of functionality is available and you can take advantage of it to make your process easier especially if you’re familiar with Javascript like a lot of programmers are. With something like this you have a re-usable script with follow the DRY ( Don’t Repeat Yourself ) principle. If you’d like to learn more about it, the MongoDB documentations is fairly straightforward and can answer many of your questions. We hope this tutorial was able to answer your question or provide you the snippet of code that you were looking for all along. Thank you for your time and if you have any feedback or questions do not hesitate to reach out to us.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.