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.


Let us quickly look into an example of Mongo Script.

  1. Start Mongo Daemon.

    Run the following command in terminal

    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.

  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 :

    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.