How to Execute Mongo Shell Commands through a Javascript File

Introduction

If you work in the MongoDB Shell, you should know that the shell is actually in interactive JavaScript shell and you can run js code directly in it or you can execute javascript from a fil. Automating a set of tasks you perform frequencly might be a good idea if you’re looking to gain some efficiency and this is one way to do that. If you’re familiar with the very popular programming language Javascript, this can be a way to leverage your skillset. In this tutorial we’ll show you step-by-step how to exeute Mongo commands from a Javascript file. We’ll show you how step-by-step but if you’d just rather see the example code, scroll down to the Just the Code section.

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 experience 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. In this tutorial our goal is to execcute a Javascript file from the MongoDB shell. The Javascript file will perform the tasks of selecting a database and printing the stats.

1. Create a starter javascript file

We will begin by creating a very simple javascript file that solely prints a message so we can verify it’s running. We will update it with more useful code later. We named our file dbStats.js because it will eventually print the stats of a database.

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

2. Execute the dbStats.js file from the MongoDB shell

Now that we have a starter js file dbStats.js let’s run it from the MongoDB shell. The commmand to do that is as follows:

$ mongo < dbStats.js

Note: Our dbStats.js file is in our current working directory. If yours is not your command would look more like:

$ mongo < /folder1/folder2/dbStats.js

Here’s the response we get from executing dbStats.js. Here we are just looking to verify that print("Running dbStats.js"); statement ran:

$ mongo < dbStats.js
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

As you can see, we do see our message in the log. This opens a lot of doors since we can now run a Javascript through the MongoDB shell.

3. Add functionality to the javascript file

Now let’s add some real functionality to our dbStats.js file. Our goal was to select the demoDatabase and then print the stats.

  • To do that first we create a new Mongo connection with default settings using new Mongo() and select our database using conn.getDB().
  • Next we print stats using db.stats(); which returns statistics about the database. Add to your javascript file.

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

conn = new Mongo(); db = conn.getDB(“demoDatabase”); db.stats(); `

We can verify this modified script works by running the script again like so

$ mongo < dbStats.js

Your results should look something like this:

MongoDB shell version v4.0.3
connecting to: mongodb://127.0.0.1:27017
Implicit session: session { "id" : UUID("0e9890ae-0281-45ab-8129-bcca25e301d0") }
MongoDB server version: 4.0.3
Running dbStats.js
connection to 127.0.0.1:27017
demoDatabase
{
        "db" : "demoDatabase",
        "collections" : 5,
        "views" : 0,
        "objects" : 22,
        "avgObjSize" : 76.36363636363636,
        "dataSize" : 1680,
        "storageSize" : 143360,
        "numExtents" : 0,
        "indexes" : 5,
        "indexSize" : 126976,
        "fsUsedSize" : 114168762368,
        "fsTotalSize" : 499963174912,
        "ok" : 1
}
bye
$

Sucess! The output is the statistics of our MongoDB cluster!

Learn More

To learn more about the working with MongoDB through Javascript we suggest you look up the MongoDB documentation directly or you can always reach out to an expert at Object Rocket to discuss your specific application. MongoDB does provide an npm library to make interacting with MongoDB really easy.

Conclusion

We showed you how to execute a JS file from the MongoDB shell and print the statistics of your MongoDB stats. This of course can be modified to do whatever your application requires. If you’d like to learn more about how MongoDB and Javascript can be used together, 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.

Just the Code

If you’re already comfortable with the tech covered in this article and just are looking for a reminder, here’s all the code we used to demonstrate how to execute a javascript file that interacts with MongoDB.

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

conn = new Mongo(); db = conn.getDB(“demoDatabase”); db.stats(); `

$ mongo < dbStats.js

Pilot the ObjectRocket Platform Free!

Try Fully-Managed Redis,
MongoDB & Elasticsearch

Get Started

OR

Try CockroachDB
in Beta

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.