Mongo Script

In this MongoDB TutorialMongo Script, we shall learn about executing multiple commands from a JavaScript file using mongo program, with the help of examples.

In our previous tutorial, we have learnt about MongoDB Shell. There is a little difference how Mongo Script execution behaves from that of a Mongo Shell. We shall learn about these differences in next tutorial.

Example – Mongo Script

Let us quickly look into an example of Mongo Script.


1. Start Mongo Daemon

Run the following command in terminal.

sudo mongod --port 27017 --dbpath /var/lib/mongodb

Now Mongo Daemon would be waiting for connections on port 27017.

2. Mongo Commands in JavaScript File

Following is a JavaScript file containing Mongo Commands. You may create it using any of your favorite text editors.


// equivalent for "use <db>" command in mongo shell
db = db.getSiblingDB('tutorialkart')
// print the collections present in tutorialkart db

3. Run the JavaScript file using Mongo Program

Open a terminal from the location of .js file and run the JavaScript file with Mongo Program as shown below.

mongo mongo-script-example.js

Console Output

~/workspace/mongo$ mongo mongo-script-example.js
MongoDB shell version v3.4.10
connecting to: mongodb://
MongoDB server version: 3.4.10

First three lines in the output mention about the mongo shell version, and the URL of the mongo server it is trying to connect to and finally once the connection is successful, it prints the mongo server version.

Given the connection to MongoDB Server is successful, the commands in the JavaScript file are executed sequentially.


In this MongoDB Tutorial, we learned how to create a JavaScript file with MongoDB code, and how to run this Mongo Script using mongo command.