Step-by-Step Guide
- Update the Package Index
Open a terminal and update the package index to ensure you have the latest information about available packages:
sudo apt update
- Import the MongoDB Public Key
Import the public key used by the package management system:
wget -qO - https://www.mongodb.org/static/pgp/server-4.4.asc | sudo apt-key add -
- Create the MongoDB Source List File
Create a list file for MongoDB. Use your preferred text editor to create the file:
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/debian buster/mongodb-org/4.4 main" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.list
- Reload the Local Package Database
Reload the package database to include the MongoDB repository:
sudo apt update
- Install MongoDB Packages
Install MongoDB using theapt
package manager:
sudo apt install -y mongodb-org
- Start and Enable MongoDB
Start the MongoDB service:
sudo systemctl start mongod
Enable MongoDB to start on boot:
sudo systemctl enable mongod
- Verify MongoDB Installation
Check the MongoDB service status to ensure it is running:
sudo systemctl status mongod
If MongoDB is running, you should see an active (running) status.
- Test MongoDB Installation
To test the MongoDB installation, use the MongoDB shell (mongo
) to connect to the MongoDB server:
mongo
Once connected, you can run basic MongoDB commands to ensure everything is working correctly. For example, create a new database and collection:
use mydatabase
db.mycollection.insertOne({ name: "MongoDB", type: "Database" })
db.mycollection.find()
You should see the inserted document in the output.
- Secure MongoDB (Optional)
For production environments, it’s important to secure your MongoDB installation. Create an administrative user:
use admin
db.createUser({
user: "admin",
pwd: "your_password",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
})
Enable authentication by editing the MongoDB configuration file:
sudo nano /etc/mongod.conf
Add or modify the following lines:
security:
authorization: enabled
Restart MongoDB to apply the changes:
sudo systemctl restart mongod
- Backup and Restore Databases (Optional)
To back up a MongoDB database, use themongodump
command:bash mongodump --db mydatabase --out /path/to/backup
To restore a database from a backup, use themongorestore
command:bash mongorestore --db mydatabase /path/to/backup/mydatabase