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.

A Mongo script is a JavaScript file that contains MongoDB shell commands. Instead of typing each command manually in the shell, you place the commands in a .js file and execute the file from the terminal. This is useful for repeated database setup, simple administration tasks, sample data loading, and quick checks during development.

Modern MongoDB installations commonly use mongosh, while older tutorials and older MongoDB versions use the legacy mongo shell. The original example below uses mongo. If your system has mongosh installed, use the mongosh command shown later in this tutorial.

When to Use a MongoDB JavaScript File

Use a MongoDB JavaScript file when you want to run a small sequence of shell commands in the same order every time. For example, you can switch to a database, create collections, insert test documents, query data, or print collection names from one script file.

  • Run the same MongoDB shell commands repeatedly without typing them again.
  • Create sample collections and documents for a local development database.
  • Group simple read, write, and verification commands in one file.
  • Share a short database setup script with another developer.
  • Load helper functions from another JavaScript file when the script grows larger.

Mongo Script Execution Pattern

The basic pattern is simple. First, make sure the MongoDB server is running. Then create a JavaScript file with MongoDB shell commands. Finally, run the file using mongo or mongosh.

</>
Copy
Start MongoDB server
Create a JavaScript file with MongoDB commands
Run the file using mongo or mongosh
Check the printed output or database changes

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.

On many current installations, MongoDB is started as a service instead of running mongod directly from the terminal. For example, on a Linux system that uses systemd, the service command may look like the following.

</>
Copy
sudo systemctl start mongod

Use the command that matches your local MongoDB installation. The important point is that the MongoDB server must be running before the script connects to it.

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.

mongo-script-example.js

</>
Copy
// equivalent for "use <db>" command in mongo shell
db = db.getSiblingDB('tutorialkart')

// print the collections present in tutorialkart db
print(db.getCollectionNames())

The line db = db.getSiblingDB('tutorialkart') selects the tutorialkart database from inside the script. This is commonly used in MongoDB shell scripts because the interactive use tutorialkart command is shell syntax, while getSiblingDB() works inside a JavaScript file.

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://127.0.0.1:27017
MongoDB server version: 3.4.10
customers,myNewCollection,people

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.

Run the Same MongoDB Script with mongosh

If you are using mongosh, run the same JavaScript file by passing the file name to the mongosh command. The following command connects to a local MongoDB server and executes the script.

</>
Copy
mongosh mongo-script-example.js

You can also pass a connection string before the script file. This is useful when the MongoDB server runs on a different host, port, or database.

</>
Copy
mongosh "mongodb://127.0.0.1:27017/tutorialkart" mongo-script-example.js

When a connection string includes the database name, the shell starts with that database selected. You can still use db.getSiblingDB() inside the script when you want to switch databases explicitly.

Mongo Script Example with Insert and Find Commands

The first example prints collection names. The next example shows a small script that inserts documents and reads them back from a collection. This demonstrates how normal MongoDB shell commands can be placed in a JavaScript file.

mongo-crud-script.js

</>
Copy
db = db.getSiblingDB('tutorialkart')

db.students.deleteMany({})

db.students.insertMany([
  { name: 'Arjun', course: 'MongoDB', score: 85 },
  { name: 'Meera', course: 'MongoDB', score: 92 },
  { name: 'Ravi', course: 'JavaScript', score: 78 }
])

const mongoStudents = db.students.find({ course: 'MongoDB' }).toArray()

printjson(mongoStudents)

Run the script using mongosh.

</>
Copy
mongosh mongo-crud-script.js

The script clears the students collection, inserts three sample documents, queries only the MongoDB course records, and prints the matching documents as JSON-like output.

[
  {
    _id: ObjectId('...'),
    name: 'Arjun',
    course: 'MongoDB',
    score: 85
  },
  {
    _id: ObjectId('...'),
    name: 'Meera',
    course: 'MongoDB',
    score: 92
  }
]

Include Another JavaScript File in a Mongo Script

For longer scripts, you may keep helper functions in a separate JavaScript file and load them into the main script. The shell provides load() for this purpose.

helpers.js

</>
Copy
function printTitle(title) {
  print('\n=== ' + title + ' ===')
}

main-script.js

</>
Copy
load('helpers.js')

db = db.getSiblingDB('tutorialkart')

printTitle('Collections in tutorialkart')
printjson(db.getCollectionNames())

Run the main script from the directory that contains both files, or provide the correct relative or absolute path to helpers.js.

Mongo Script Notes for Writing Reliable Shell Scripts

  • Use db.getSiblingDB('databaseName') in a script instead of relying only on interactive shell commands.
  • Use print() or printjson() to show useful progress and query results while the script runs.
  • Keep destructive commands such as deleteMany() or drop() clearly visible and limited to test data unless you intentionally need them.
  • Use a connection string when the script must connect to a specific host, port, authentication database, or database.
  • Prefer mongosh for current MongoDB shell scripting unless you are working with an older environment that still uses the legacy mongo shell.

Mongo Script FAQs

How do I execute a JS file in MongoDB?

Save the MongoDB shell commands in a .js file and run it with mongosh file-name.js. In older environments, the command may be mongo file-name.js.

Can I use JavaScript in MongoDB shell scripts?

Yes. MongoDB shell scripts are JavaScript files. You can use JavaScript variables, functions, arrays, loops, and MongoDB shell methods such as db.collection.find(), insertMany(), and getSiblingDB().

How do I select a database inside a Mongo script?

Inside a script, use db = db.getSiblingDB('databaseName'). This is the script-friendly equivalent of switching databases in the interactive shell.

How can I retrieve data from MongoDB using a JavaScript file?

Use a query method such as find() or findOne() inside the script. For example, db.students.find({ course: 'MongoDB' }).toArray() retrieves matching documents from the students collection.

Can one Mongo script load another JavaScript file?

Yes. Use load('file-name.js') from the main script. This is useful for loading helper functions before running the rest of the MongoDB commands.

Editorial QA Checklist for Mongo Script Tutorial

  • Confirm that the tutorial distinguishes the legacy mongo shell from the current mongosh command.
  • Check that any newly added command-line examples use language-bash and output-only examples use output.
  • Verify that the script examples use db.getSiblingDB() for database selection inside JavaScript files.
  • Confirm that CRUD examples use safe sample data and clearly show what the script deletes or inserts.
  • Check that the FAQs answer how to execute a JS file, how JavaScript is used, how to select a database, how to retrieve data, and how to load another script.

Conclusion

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.

A Mongo script is useful when several MongoDB shell commands need to be executed together. For current environments, run the script with mongosh. For older environments, the legacy mongo command may still be used.