Database
MongoDB
What is MongoDB?
MongoDB is a NoSQL database that stores data in flexible, JSON-like documents. It is a popular choice for developers because it is easy to use and can handle large amounts of data. MongoDB is a document database, which means it stores data in documents instead of tables. Each document is a JSON object that contains key-value pairs. MongoDB is a schema-less database, which means you do not need to define a schema before you start storing data. This makes it easy to store and retrieve data without having to worry about the structure of the data.
Install MongoDB Community Edition
Ubuntu Server
MongoDB 8.0 Community Edition supports the following 64-bit Ubuntu LTS (Long-Term Support) releases:
- 24.04 LTS ("Noble")
- 22.04 LTS ("Jammy")
- 20.04 LTS ("Focal")
- Make sure your Ubuntu system version is supported by MongoDB 8.0 Community Edition. You can check the Ubuntu version by running the following command:
> lsb_release -a
#or
> cat /etc/lsb-release
- Install dependencies
> sudo apt-get install gnupg curl
- Import the public key used by the package management system
curl -fsSL https://www.mongodb.org/static/pgp/server-8.0.asc | \
sudo gpg -o /usr/share/keyrings/mongodb-server-8.0.gpg \
--dearmor
- Create a list file for MongoDB
Ubuntu 24.04 LTS ("Noble")
> 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
Ubuntu 22.04 LTS ("Jammy")
> echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/8.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.0.list
Ubuntu 20.04 LTS ("Focal")
> echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/8.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.0.list
- Reload the local package database
> sudo apt update
- Install the MongoDB packages
> sudo apt install -y mongodb-org
- Start MongoDB
> sudo systemctl start mongod
If you receive an error message, you may need to enable and start the service:
Failed to start mongod.service: Unit mongod.service not found.
Run the following command and repeat the previous step:
> sudo systemctl daemon-reload
- Verify that MongoDB has started successfully
> sudo systemctl status mongod
- Enable MongoDB to start on boot
> sudo systemctl enable mongod
- Stop MongoDB
sudo systemctl stop mongod
- Restart MongoDB
> sudo systemctl restart mongod
Use mongosh
to connect to the MongoDB shell.
macOS
- Install Homebrew (if not already installed)
> /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
- Install MongoDB 8.0 Community Edition
Since MongoDB 4.4.1,MongoDB Database Tools is included in the MongoDB Community Edition when installed via Homebrew.
> brew tap mongodb/brew
> brew update
> brew install mongodb-community@8.0
Intel | Apple Silicon | |
---|---|---|
Config File | /usr/local/etc/mongod.conf | /opt/homebrew/etc/mongod.conf |
log directory | /usr/local/var/log/mongodb | /opt/homebrew/var/log/mongodb |
data directory | /usr/local/var/mongodb | /opt/homebrew/var/mongodb |
Run MongoDB
You can run MongoDB as a macOS service using brew, or you can run MongoDB manually as a background process. It is recommended to run MongoDB as a macOS service, as doing so sets the correct system ulimit values automatically (see ulimit settings for more information).
Start MongoDB Community Edition
> brew services start mongodb-community@8.0
Stop MongoDB Community Edition
> brew services stop mongodb-community@8.0
Uninstall MongoDB
Ubuntu
- Stop the MongoDB service
> sudo service mongod stop
- Remove MongoDB packages
> sudo apt-get purge mongodb-org*
- Remove data directories
> sudo rm -r /var/log/mongodb
> sudo rm -r /var/lib/mongodb
Configuration
The MongoDB configuration file is located at /etc/mongod.conf
on Ubuntu and /usr/local/etc/mongod.conf
on macOS.
# mongod.conf
# for documentation of all options, see:
# http://docs.mongodb.org/manual/reference/configuration-options/
# Where and how to store data.
storage:
dbPath: /var/lib/mongodb
# engine:
# wiredTiger:
# 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
# how the process runs
processManagement:
timeZoneInfo: /usr/share/zoneinfo
#security:
#operationProfiling:
#replication:
#sharding:
## Enterprise-Only Options:
#auditLog:
Connect to MongoDB
> mongosh
# or
> mongosh "mongodb://localhost:27017"
If you need to connect to a custom port, use the following command:
> mongosh "mongodb://localhost:28015"
# or
> mongosh --port 28015
If you need to connect to a remote server, use the following command:
> mongosh "mongodb://mongodb0.example.com:28015"
# or
> mongosh --host mongodb0.example.com --port 28015
Database
When you first log in to mongosh, the test> prompt appears because MongoDB defaults to using the test database if no specific database is specified in the connection string or selected explicitly.
What is the test Database?
- The test database is a default database provided by MongoDB for general use.
- is often used for quick tests or experiments since it doesn’t require explicit creation—you can start working with it immediately.
Why does test> appear?
- When you connect to a MongoDB server, mongosh automatically sets the context to a database.
- If no database is explicitly selected, it defaults to test.
If you’d like to start in a specific database upon logging in, include the database name in your connection string. For example:
> mongosh "mongodb://localhost:27017/mydatabase"
Create Database
In MongoDB, switching to a database that doesn’t exist yet will create it as soon as you perform an operation (like inserting data). Use the use command:
> use newDatabase
- Replace newDatabase with your desired database name.
- At this point, the database is not yet created—it will be created when you insert data.
> db.collection_name.insertOne({ key: "value" })
# Example:
> db.users.insertOne({ name: "John Doe", email: "john@example.com" })
List Databases
> show dbs
Delete Database
> use newDatabase
> db.dropDatabase()
Collection
Create a Collection
> db.createCollection('myCollection')
Drop a Collection
> db.users.drop()
User
List Users
> db.system.users.find().pretty()
Create a User
> db.createUser({
user: "myUser",
pwd: "mySecurePassword",
roles: [
{ role: "readWrite", db: "newDatabase1" },
{ role: "read", db: "newDatabase2" },
]
})
Or use the passwordPrompt() function to securely enter the password:
> db.createUser({
user: "myUser",
pwd: passwordPrompt(),
roles: [
{ role: "readWrite", db: "newDatabase1" },
{ role: "read", db: "newDatabase2" },
]
})
Example output:
{ ok: 1 }
Verify User
List all users in the current database to verify the creation:
> db.getUsers()
Exit MongoDB Shell
> exit
MongoDB in Node.js
mongodb://<username>:<password>@<host>:<port>/<database>?options
CRUD Operations
Languages
PHP
- Install the MongoDB PHP driver
> sudo pecl install mongodb
- Add the following line to your php.ini file:
extension=mongodb.so
- Require Composer Package
> composer require mongodb/laravel-mongodb