How to run MongoDB commands from bash script (with examples)

Updated: February 3, 2024 By: Guest Contributor Post a comment

Introduction

MongoDB, a popular NoSQL database, offers robust features for dealing with JSON-like documents. Despite having a powerful shell, mongodb-cli, and drivers for various programming languages, sometimes quick shell automation is preferred. Bash scripting, a powerful part of Linux and Unix systems, allows you to automate command execution.

Running MongoDB commands from a bash script can streamline database maintenance, automate repetitive tasks, and orchestrate complex operations. In this tutorial, we will cover the basics of writing bash scripts to interact with MongoDB and provide practical examples to illustrate how to accomplish various tasks.

Prerequisites

  • A running MongoDB instance.
  • Basic knowledge of shell scripting.
  • Knowledge of MongoDB CRUD operations.

Executing Simple MongoDB Commands

The most straightforward way to run a MongoDB command from a bash script is by using the mongo executable with the --eval flag, which allows you to pass a JavaScript expression directly to the MongoDB shell.

#!/bin/bash
echo "Running a simple MongoDB command"
mongo --eval 'db.runCommand({ping: 1})';

This code will output something like:

{ "ok" : 1 }

Inserting Documents

Let’s create a script that inserts a new document into a collection named users.

#!/bin/bash

dbName="mydb"
collectionName="users"
document='{"name":"John Doe","age":30,"city":"New York"}'

mongo $dbName --eval "db.$collectionName.insert($document)"

When run, the script will insert the document into the specified collection and output the result of the insertion.

Running Scripts with mongo Shell

You might also want to run an external JavaScript file containing multiple MongoDB commands. Use the mongo command without the --eval flag and specify the JavaScript file.

#!/bin/bash

scriptPath="path/to/your/script.js"

mongo $dbName $scriptPath

The JavaScript file may contain:

db.users.insertOne({ name: "Jane Doe", age: 25, city: "Los Angeles" });
db.products.updateOne({ _id: ObjectId("507f191e810c19729de860ea") },
 { $set: { stock: 10 } });
db.orders.remove({ status: "Cancelled" });

Backup and Restore Operations

Bash scripting can be particularly useful for database backups and restores using mongodump and mongorestore. Here’s an example of a backup script:

#!/bin/bash

backupDir="/path/to/backup/dir"

date=$(date +"%m-%d-%y")
# Backup the database
echo "Creating backup for $dbName on $date"
mongodump --db $dbName --out $backupDir/$date

To restore the database:

#!/bin/bash

backupDir="/path/to/backup/dir"

dateToRestore="01-01-23"

echo "Restoring $dbName from backup on $dateToRestore"
mongorestore --db $dbName $backupDir/$dateToRestore/$dbName

Advanced Usage: Automation with Loops

Advanced scripts can include loops, reading from files, and conditional logic. Here’s an example that iterates over a list of collections to back them up individually:

#!/bin/bash

backupDir="/path/to/backup/"
collections=("users" "orders" "products")

date=$(date +"%m-%d-%y")
for collection in "${collections[@]}"
do
    echo "Backing up $collection"
    mongodump --db $dbName --collection $collection --out $backupDir/$date

done

Handling User Inputs and Arguments

Incorporating user input can make your scripts interactive. The following example shows how you can accept database and collection names as arguments.

#!/bin/bash

if [ "$#" -ne 2 ]; then
    echo "Usage: $0  "
    exit 1
fi

dbName=$1
collectionName=$2

mongo --eval "printjson(db.$collectionName.stats())" $dbName

Error Handling

Solid error handling is crucial in scripts. Check the exit status of each MongoDB command to ensure your operations succeed.

#!/bin/bash
echo "Running a MongoDB command with error handling"
mongo --eval 'db.runCommand({ping: 1})'

if [ "${?}" -ne 0 ]; then
    echo "MongoDB command failed";
    exit 1;
else
    echo "MongoDB command executed successfully";
fi

Automation with Cron

Finally, for automation, you can pair your bash scripts with cron jobs to schedule tasks. The following cron job runs a backup script every day at midnight:

# In your crontab0 0 * * * /path/to/your/backup_script.sh

Conclusion

We have explored how to unleash the potential of MongoDB operations within bash scripts, providing examples from basic to more advanced applications. These fundamental concepts can be applied to automate your database tasks efficiently and reliably. Remember to secure your scripts, especially if they contain sensitive information, and always test your scripts thoroughly before using them in a production environment.