Introduction to MongoDB
Overview
MongoDB is a popular NoSQL database system that uses a document-oriented data model. It’s designed for scalability, flexibility, and ease of development. This guide provides a practical approach to installing and configuring MongoDB on various operating systems including Windows, macOS, and Linux.
Installation
Windows Installation
Download MongoDB:
Install MongoDB:
.msi
file.Setup Environment Variables:
bin
directory to your system’s PATH environment variable:
C:Program FilesMongoDBServer<version>bin
Start MongoDB:
net start MongoDB
macOS Installation
Install via Homebrew:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
brew tap mongodb/brew
brew install mongodb-community
Start MongoDB:
brew services start mongodb/brew/mongodb-community
Linux Installation (Ubuntu as an example)
Import the public key used by the package management system:
wget -qO - https://www.mongodb.org/static/pgp/server-5.0.asc | sudo apt-key add -
Create a list file for MongoDB:
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/5.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-5.0.list
Reload local package database:
sudo apt-get update
Install MongoDB packages:
sudo apt-get install -y mongodb-org
Start MongoDB:
sudo systemctl start mongod
Enable MongoDB to start on boot:
sudo systemctl enable mongod
Configuration
Configuration File (mongod.conf)
Location:
C:Program FilesMongoDBServer<version>binmongod.cfg
/etc/mongod.conf
Editing the Configuration:
mongod.conf
. Below is an example configuration:
# mongod.conf
# Where and how to store data.
storage:
dbPath: /var/lib/mongodb
journal:
enabled: true
# Where to write logging data.
systemLog:
destination: file
logAppend: true
path: /var/log/mongodb/mongod.log
# network interfaces
net:
port: 27017
bindIp: 127.0.0.1
# Process Management Options
processManagement:
timeZoneInfo: /usr/share/zoneinfo
Apply Configuration Changes:
net stop MongoDB
net start MongoDB
sudo systemctl restart mongod
Verification
Verify MongoDB is running:
mongo
Check MongoDB status:
net start MongoDB
sudo systemctl status mongod
By following these detailed instructions, you will have MongoDB installed and configured on your operating system, ready for development and educational purposes.
Preparing Your Environment
In this section, we will cover preparing your system to work effectively with MongoDB after installation. This includes starting and stopping the MongoDB service, connecting to the MongoDB server, and creating a basic database and collection.
Starting and Stopping the MongoDB Service
On Windows
Starting MongoDB:
net start MongoDB
Stopping MongoDB:
net stop MongoDB
On macOS
Starting MongoDB using Homebrew:
brew services start mongodb/brew/mongodb-community
On Linux (systemd)
Starting MongoDB:
sudo systemctl start mongod
Stopping MongoDB:
sudo systemctl stop mongod
Connecting to MongoDB Server
After starting the MongoDB service, you can connect to the MongoDB server using the mongo
shell.
Mongo Shell Command
mongo
Executing the above command in your terminal will start the MongoDB shell and connect to the default mongod
instance running on localhost
at port 27017
.
Creating a Basic Database and Collection
Once connected to the MongoDB shell, you can create a database and a collection.
Create a Database
use myNewDatabase
The use
command switches your context to myNewDatabase
. If myNewDatabase
does not exist, it will be created when you insert some data into it.
Create a Collection
db.createCollection("myNewCollection")
This command will create a collection named myNewCollection
within the myNewDatabase
.
Insert Data into Collection
db.myNewCollection.insertOne({ name: "MongoDB", type: "Database", year: 2009 })
This command inserts a single document into myNewCollection
.
Verification
To verify that your database and collection have been created, you can use the following commands:
Show Databases
show dbs
Show Collections in the Current Database
show collections
Query the Collection
db.myNewCollection.find().pretty()
This will display the documents in a readable format.
Use these steps to ensure that your MongoDB environment is correctly prepared and that you can interact with the database as intended.
Part 3: Installing MongoDB on Windows
This section will provide a practical guide for installing MongoDB on a Windows operating system. Before starting, ensure that you have administrative access on your Windows machine.
Step-by-Step Installation Guide
1. Download MongoDB
2. Run the .msi Installer
3. Configure the Installation
In the Service Configuration step, you can choose to run MongoDB as a service:
C:Program FilesMongoDBServer{Version}data
.C:Program FilesMongoDBServer{Version}log
.Note: Make sure you have created the above-mentioned directories or choose an existing one.
(Optional) Install MongoDB Compass:
Complete the installation by clicking the “Install” button.
4. Add MongoDB to the System Path
Path
variable and select it, then click “Edit”.bin
directory. By default, it is:
C:Program FilesMongoDBServer{Version}bin
5. Verify the Installation
cmd
).mongo --version
and press Enter.This should display the version of MongoDB installed, verifying a successful installation.
Configuration
1. Create Configuration File
Open a text editor and create a configuration file named mongo.cfg
.
Add the following basic configuration, modifying paths as necessary:
systemLog:
destination: file
path: C:Program FilesMongoDBServer{Version}logmongod.log
logAppend: true
storage:
dbPath: C:Program FilesMongoDBServer{Version}data
net:
bindIp: 127.0.0.1
port: 27017
2. Run MongoDB with Configuration File
cmd
).mongod --config "C:Program FilesMongoDBServer{Version}mongo.cfg"
This will start the MongoDB server based on the configurations provided in the mongo.cfg
file.
Conclusion
You have successfully installed and configured MongoDB on your Windows machine. You can now start building and managing your MongoDB databases.
Installing MongoDB on macOS
Here is a practical step-by-step guide to installing MongoDB on a macOS system.
Prerequisites
Ensure you have Homebrew installed on your macOS. If not, you can install it by running the following command in the Terminal:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
Steps for Installation
Update Homebrew
Make sure your Homebrew is up to date by running:brew update
Install MongoDB
To install the latest version of MongoDB, execute the following command:brew tap mongodb/brew
brew install mongodb-community@5.0This will install MongoDB 5.0, which is the latest stable version at the time of writing.
Verify the Installation
Confirm that MongoDB has been installed correctly by checking the version:mongod --version
Run MongoDB as a Service
To start MongoDB automatically as a service, use the following commands:brew services start mongodb/brew/mongodb-community
You can stop the service using:
brew services stop mongodb/brew/mongodb-community
To check the status of the MongoDB service:
brew services list
Running MongoDB Manually
If you prefer to run MongoDB manually, you can start the MongoDB server by running:mongod --config /usr/local/etc/mongod.conf
To stop the MongoDB server, you can terminate the mongod process.
Connect to MongoDB
Open a new Terminal window/tab and launch the MongoDB shell to connect to the MongoDB instance:mongo
This connects to the running instance of MongoDB and allows you to execute database operations.
Configuration
Default Configuration File
The default configuration file for MongoDB is usually located at
/usr/local/etc/mongod.conf
. You can edit this file to change configurations such as the data directory, log path, and bind IP address. Here is a quick way to open it via a text editor:nano /usr/local/etc/mongod.conf
Example configuration snippet:
storage:
dbPath: /usr/local/var/mongodb
systemLog:
destination: file
path: /usr/local/var/log/mongodb/mongo.log
logAppend: true
net:
bindIp: 127.0.0.1Creating Data and Log Directories
Ensure the directories specified in your configuration file exist:
mkdir -p /usr/local/var/mongodb
mkdir -p /usr/local/var/log/mongodbAdjust the permissions if needed:
sudo chown -R `id -un` /usr/local/var/mongodb
sudo chown -R `id -un` /usr/local/var/log/mongodb
Final Verification
Check the MongoDB server status by accessing the MongoDB shell and running sample queries or commands to verify full functionality:
mongo
You should see a prompt similar to:
MongoDB shell version v5.0.x
connecting to: mongodb://127.0.0.1:27017/
...
> show dbs
And that’s it! You’ve successfully installed and configured MongoDB on macOS.
Part 5: Installing MongoDB on Linux
Step-by-Step Installation
Here’s how you can install MongoDB on a Linux system:
Import the MongoDB public GPG Key
wget -qO - https://www.mongodb.org/static/pgp/server-4.4.asc | sudo apt-key add -
Create a list file for MongoDB
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/4.4 multiverse" |
sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.listReload local package database
sudo apt-get update
Install MongoDB packages
sudo apt-get install -y mongodb-org
Start MongoDB
sudo systemctl start mongod
Enable MongoDB to start on system reboot
sudo systemctl enable mongod
Verify that MongoDB has started
You can check the status of the MongoDB service with the following command:
sudo systemctl status mongod
If everything is set up correctly, you should see a status that indicates MongoDB is active and running.
Configuration
After installation, you might want to configure MongoDB to suit your needs. Configuration files are generally found at /etc/mongod.conf
.
Example Configuration (Optional Changes):
Open Configuration File
sudo nano /etc/mongod.conf
Modify BindIp to Allow Remote Connections (Optional)
net:
bindIp: 0.0.0.0Set Up Authentication (Optional)
Edit the Security section to enable authentication.
security:
authorization: "enabled"Restart MongoDB to Apply Changes
sudo systemctl restart mongod
Security Considerations
Create an Admin User:
After enabling authentication, create an admin user:
use admin
db.createUser({
user: "myAdmin",
pwd: "securePassword",
roles: [{ role: "userAdminAnyDatabase", db: "admin" }]
})Connecting with Authentication:
When authentication is enabled, use the
-u
(username) and-p
(password) options:mongo -u "myAdmin" -p "securePassword" --authenticationDatabase "admin"
Conclusion
Following these steps will install MongoDB on your Linux system, start the service, and optionally configure it for remote connections and authentication. Ensure to restart the MongoDB service after any configuration changes for them to take effect.
Post-Installation Configuration and Management of MongoDB
Configuration
Modify
mongod.conf
Configuration FileThe
mongod.conf
file is where you set most of MongoDB’s operational parameters. Typical locations:- Linux:
/etc/mongod.conf
- Windows:
C:Program FilesMongoDBServer<version>binmongod.cfg
- macOS:
/usr/local/etc/mongod.conf
Example of a
mongod.conf
:storage:
dbPath: /var/lib/mongo
journal:
enabled: true
systemLog:
destination: file
logAppend: true
path: /var/log/mongodb/mongod.log
net:
port: 27017
bindIp: 127.0.0.1 # Change to 0.0.0.0 to allow external connections
security:
authorization: enabled- Linux:
Enabling Authentication
Verify that the
authorization
field is set toenabled
under thesecurity
section:security:
authorization: enabledRestart the MongoDB service to apply the changes.
User Management
Create Admin User
Open the MongoDB shell and connect to the
admin
database:mongo
use adminCreate an admin user:
db.createUser({
user: "admin",
pwd: "securepassword",
roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
});Create Application-Specific User
Switch to the target database:
use myAppDB
Create the user:
db.createUser({
user: "appUser",
pwd: "appUserPwd",
roles: [ { role: "readWrite", db: "myAppDB" } ]
});
Service Management
Start and Stop MongoDB Service
- Linux:
sudo systemctl start mongod
sudo systemctl stop mongod - Windows:
net start MongoDB
net stop MongoDB - macOS:
brew services start mongodb/brew/mongodb-community
brew services stop mongodb/brew/mongodb-community
- Linux:
Enable MongoDB to Start on Boot
- Linux:
sudo systemctl enable mongod
- Windows:
sc config MongoDB start= auto
- macOS:
brew services start mongodb/brew/mongodb-community
- Linux:
Backup and Restore
Backup MongoDB Database
Use
mongodump
utility:mongodump --uri="mongodb://admin:securepassword@localhost:27017" --out=/path/to/backup/
Restore MongoDB Database
Use
mongorestore
utility:mongorestore --uri="mongodb://admin:securepassword@localhost:27017" /path/to/backup/
Monitoring and Maintenance
Monitor the MongoDB Logs
- Linux and macOS:
tail -f /var/log/mongodb/mongod.log
- Windows:
Open the log file at the specified path in a text editor, typically:C:Program FilesMongoDBServer<version>logmongod.log
- Linux and macOS:
Check Database Health
Connect to MongoDB shell and run the following:
use admin
db.serverStatus()
db.runCommand({ dbStats: 1 })Rotate Logs
Issue a log rotation command as MongoDB does not rotate logs by default:
db.adminCommand({ logRotate: 1 })
By following the steps outlined above, you can ensure that MongoDB is not only configured properly but also secured through user management and maintainable through proper service management and backup practices.