How To Install and Secure MongoDB

By Anurag Singh

Updated on Feb 13, 2025

How To Install and Secure MongoDB

In this tutorial, we'll learn how to install and secure MongoDB and perform basic CRUD operations.

Below is a detailed, step-by-step tutorial covering MongoDB installation, basic administration (including security and CRUD operations), and setting up replication. This guide is written with IT professionals in mind, explaining each concept so that even if you’re new to MongoDB, you’ll be able to follow along.

How to install and secure MongoDB

Update Your Package List

Open a terminal and run:

sudo apt update

This ensures your package list is up to date.

Install MongoDB on Ubuntu Server

Import MongoDB’s Public GPG Key:

MongoDB signs its packages so that your system can verify their authenticity.

curl -fsSL https://www.mongodb.org/static/pgp/server-8.0.asc | \
   sudo gpg -o /usr/share/keyrings/mongodb-server-8.0.gpg \
   --dearmor

Add MongoDB’s repository to your system so you can install the latest version. For Ubuntu 20.04 (Focal), run:

echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg ] https://repo.mongodb.org/apt/ubuntu noble/mongodb-org/8.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.0.list

Install MongoDB Packages

Update the package list again and install MongoDB:

sudo apt update
sudo apt install -y mongodb-org

Start and Enable the MongoDB Service:

Start MongoDB and enable it to launch automatically at boot:

sudo systemctl start mongod
sudo systemctl enable mongod

Verify the service status:

sudo systemctl status mongod

You should see that the service is running.

Access the MongoDB Shell

Test your installation by entering the MongoDB shell:

mongosh

You’ll enter an interactive shell where you can execute MongoDB commands.

Securing MongoDB

By default, MongoDB does not enforce authentication, meaning anyone who can connect might access or modify data. Let’s secure it by enabling authentication and creating an administrative user.

Edit the Configuration File:

Open the MongoDB configuration file (typically located at /etc/mongod.conf):

sudo nano /etc/mongod.conf

Under the security section, add the following line:

security:
  authorization: "enabled"

This setting forces MongoDB to require valid credentials for operations. Save and exit the file.

Create an Admin User

Restart MongoDB for the changes to take effect:

sudo systemctl restart mongod

Now connect to the MongoDB shell:

mongosh

Switch to the admin database and create a new user:

db.createUser({
  user: "admin",
  pwd: "YourStrongPassword", // Replace with a secure password
  roles: [
    { role: "userAdminAnyDatabase", db: "admin" },
    "readWriteAnyDatabase"
  ]
})

This command creates an administrative user with the privileges to manage users and perform read/write operations across databases.

Verify Authentication:

Exit the shell and reconnect using the new credentials:

mongosh -u admin -p YourStrongPassword --authenticationDatabase admin

You should now be connected securely with authentication enabled.

Additional Security Tips

Bind IP Address: In /etc/mongod.conf, under the net section, you can limit connections to specific IP addresses. For example, to allow only localhost:

net:
  bindIp: 127.0.0.1

Firewall Rules: Ensure that your server’s firewall restricts access to MongoDB’s default port (27017) from untrusted networks.

TLS/SSL: For production environments, consider setting up TLS/SSL to encrypt data in transit.

Basic CRUD Operations

CRUD stands for Create, Read, Update, and Delete—four basic functions to interact with your data.

Creating and Inserting Documents:

use myDatabase
db.myCollection.insertOne({ name: "Alice", age: 30, role: "developer" })

Insert Multiple Documents:

db.myCollection.insertMany([
  { name: "Bob", age: 25, role: "designer" },
  { name: "Charlie", age: 35, role: "manager" }
])

This will create a new database named myDatabase (if it doesn’t already exist) and a collection named myCollection.

Retrieve All Documents

db.myCollection.find({})

Query Specific Documents:

For example, find users older than 28:

db.myCollection.find({ age: { $gt: 28 } })

You can also format the output for easier reading:

db.myCollection.find({}).pretty()

Updating Documents:

Update a Single Document:

Suppose you want to update Alice’s age:

db.myCollection.updateOne(
  { name: "Alice" },
  { $set: { age: 31 } }
)

Update Multiple Documents:

Increase the age of all users by 1:

db.myCollection.updateMany(
  {},
  { $inc: { age: 1 } }
)

Deleting Documents:

Delete a Single Document:

db.myCollection.deleteOne({ name: "Bob" })

Delete Multiple Documents:

db.myCollection.deleteMany({ role: "manager" })

Use these operations with care, as deletions are irreversible.

Final Thoughts

In this tutorial, we've learnt how to install and secure MongoDB. By following these steps, you now have a basic understanding of how to install MongoDB, secure it with authentication and proper network configurations, perform CRUD operations, and set up a replica set for high availability. Each step builds on fundamental MongoDB administration practices, giving you a robust foundation for both development and production environments.

Remember that while this guide covers the essentials, MongoDB offers a rich ecosystem of features (like sharding, advanced indexing, and aggregation pipelines) that you can explore as your needs grow.

Happy coding and database managing!

Checkout our dedicated servers India, Instant KVM VPS, and cPanel Hosting India