How to Set Up MongoDB in Ubuntu
MongoDB is one of the most popular NoSQL databases for modern web apps, APIs, dashboards, and data-heavy services. On Ubuntu, the cleanest way to install it is through MongoDB’s official apt repository rather than the package that ships with Ubuntu itself, because MongoDB’s official packages are maintained by MongoDB Inc. and the Ubuntu mongodb package conflicts with mongodb-org. The current official Ubuntu tutorial for Community Edition covers Ubuntu 24.04, 22.04, and 20.04 LTS for MongoDB 8.0, and the install flow is built around the apt package manager.
This guide walks you through the full process: preparing Ubuntu, adding the MongoDB repository, installing the server and shell, starting the service, connecting with mongosh, creating a secure admin user, and tuning the configuration for local or remote use. The commands below are based on MongoDB’s official documentation, with practical explanations around them so the steps are easier to follow in real life.
What you are setting up
A typical MongoDB setup on Ubuntu includes these pieces:
mongod: the database server process.mongosh: the MongoDB Shell you use to connect and run commands./etc/mongod.conf: the main configuration file when MongoDB is installed from packages./var/lib/mongodb: the default data directory./var/log/mongodb: the default log directory.
MongoDB’s official package set also includes mongodb-org, which is a metapackage that pulls in the server components and tools, and mongodb-mongosh, which contains the MongoDB shell.
Before you start
The official Ubuntu installation instructions assume an LTS release and a 64-bit system. MongoDB 8.0 Community Edition supports Ubuntu 24.04 LTS, 22.04 LTS, and 20.04 LTS on x86_64, and ARM64 on select platforms. You can check your Ubuntu release with:
cat /etc/lsb-releaseThat is the same check MongoDB’s docs recommend for confirming your Ubuntu version.
If you already installed Ubuntu’s own mongodb package, remove it before using the official repository. MongoDB’s documentation is explicit that Ubuntu’s package conflicts with the official mongodb-org package.
Step 1: Remove any conflicting MongoDB package
If MongoDB was installed from Ubuntu’s default repositories, remove that package first. The official docs warn that it conflicts with MongoDB’s own packages.
A safe cleanup pattern is:
sudo apt-get remove mongodb
sudo apt-get purge mongodb
sudo apt-get autoremoveThis is a practical cleanup step before using the official MongoDB repository. The important part is that the Ubuntu package should not remain installed alongside mongodb-org.
Step 2: Install prerequisite tools
MongoDB’s installation instructions begin by making sure gnupg and curl are available, because you need them to import the repository signing key.
Run:
sudo apt-get update
sudo apt-get install gnupg curlThis prepares the system for the repository setup that comes next.
Step 3: Import MongoDB’s GPG key
The repository must be signed so apt can verify packages. MongoDB’s official instructions for Ubuntu 8.0 use the 8.0 signing key and store it under /usr/share/keyrings/.
Use:
curl -fsSL https://pgp.mongodb.com/server-8.0.asc | \
sudo gpg -o /usr/share/keyrings/mongodb-server-8.0.gpg \
--dearmorThat command is part of the official installation flow for MongoDB 8.0 Community Edition on Ubuntu.
Step 4: Add the MongoDB repository
Now you add the MongoDB repository list file for your Ubuntu version. MongoDB’s docs provide separate entries for Ubuntu 24.04 (Noble), 22.04 (Jammy), and 20.04 (Focal).
For Ubuntu 24.04:
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
For Ubuntu 22.04:
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
For Ubuntu 20.04:
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
MongoDB’s repository file name in the docs is /etc/apt/sources.list.d/mongodb-org-8.0.list.
Step 5: Refresh package lists
After adding the repository, refresh apt so Ubuntu can see the new MongoDB packages.
sudo apt-get update
This is the standard package index refresh before installation.
Step 6: Install MongoDB Community Edition
MongoDB’s official Ubuntu guide gives two installation patterns: install the latest stable release, or install a specific version by listing each package explicitly.
To install the latest stable version:
sudo apt-get install -y mongodb-org
That metapackage pulls in the official MongoDB server stack.
If you want a specific release, MongoDB’s documentation shows the format of the full install command, where each component package is pinned to the same version. In the current docs, the example shown is 8.0.12.
Example:
sudo apt-get install -y \
mongodb-org=8.0.12 \
mongodb-org-database=8.0.12 \
mongodb-org-server=8.0.12 \
mongodb-mongosh \
mongodb-org-shell=8.0.12 \
mongodb-org-mongos=8.0.12 \
mongodb-org-tools=8.0.12 \
mongodb-org-database-tools-extra=8.0.12
MongoDB also notes that if you install only mongodb-org=8.0.12 without the other matching component packages, the newest version of each component can still be installed.
If you want to prevent automatic package upgrades, MongoDB’s docs show package hold commands using dpkg --set-selections.
echo "mongodb-org hold" | sudo dpkg --set-selections
echo "mongodb-org-database hold" | sudo dpkg --set-selections
echo "mongodb-org-server hold" | sudo dpkg --set-selections
echo "mongodb-mongosh hold" | sudo dpkg --set-selections
echo "mongodb-org-mongos hold" | sudo dpkg --set-selections
echo "mongodb-org-cryptd hold" | sudo dpkg --set-selections
echo "mongodb-org-tools hold" | sudo dpkg --set-selections
echo "mongodb-org-database-tools-extra hold" | sudo dpkg --set-selections
Step 7: Start MongoDB
MongoDB runs as a service on Ubuntu. On systems using systemd, MongoDB’s docs instruct you to start the mongod service with systemctl.
sudo systemctl start mongod
If you see the error Unit mongod.service not found, MongoDB’s documentation says to run sudo systemctl daemon-reload and try starting it again. (MongoDB)
sudo systemctl daemon-reload
sudo systemctl start mongod
Then check the service status:
sudo systemctl status mongod
The documentation also shows sudo systemctl enable mongod if you want MongoDB to start automatically on reboot.
sudo systemctl enable mongod
To stop or restart the service:
sudo systemctl stop mongod
sudo systemctl restart mongod
MongoDB also documents the older System V init commands for environments that use service instead of systemctl, but on recent Ubuntu releases systemd is the common path.
Step 8: Verify the server is running
MongoDB’s docs recommend checking both the service state and the log file. On Ubuntu, the default log file is /var/log/mongodb/mongod.log. A healthy running instance typically shows the message that it is waiting for connections on port 27017.
You can check with:
sudo systemctl status mongod
sudo tail -n 50 /var/log/mongodb/mongod.log
The logs are especially useful if the service starts and then immediately stops. MongoDB’s docs explicitly call out the log file as a place to watch for errors and status messages.
Step 9: Connect with mongosh
MongoDB’s shell, mongosh, is the modern way to interact with the database from the terminal. The shell documentation describes it as a JavaScript and Node.js REPL for MongoDB deployments locally or remotely.
For a local default installation, you can connect simply by running:
mongosh
MongoDB’s shell docs say that this is equivalent to connecting to mongodb://localhost:27017.
Once connected, try a few basic commands:
show dbs
use demo_app
db.users.insertOne({ name: "Hassan", role: "admin", createdAt: new Date() })
db.users.find()
This is a good sanity check that the server is alive and that you can read and write data. The shell supports normal local connections on port 27017, and the docs also show how to connect to remote deployments with host and port options.
For a remote host:
mongosh --host mongodb0.example.com --port 27017
And for authenticated access:
mongosh --username alice --authenticationDatabase admin
MongoDB’s shell docs say that when a deployment requires authentication, you use --username and --authenticationDatabase, and mongosh prompts you for the password.
Step 10: Understand the default configuration file
When MongoDB is installed from apt, it ships with /etc/mongod.conf. MongoDB’s documentation says the default config file is already provided by the package, and changes only take effect after restarting the instance.
That file is YAML-based, and MongoDB warns that YAML does not support tabs for indentation.
A simplified example looks like this:
systemLog:
destination: file
path: "/var/log/mongodb/mongod.log"
logAppend: true
storage:
dbPath: /var/lib/mongodb
net:
bindIp: 127.0.0.1
port: 27017
MongoDB’s docs note that the Linux package init scripts depend on specific values for systemLog.path, storage.dbPath, and processManagement.fork, so changing the defaults without understanding those dependencies can prevent mongod from starting.
If you edit the configuration file, restart MongoDB afterward:
sudo systemctl restart mongod
MongoDB’s docs state clearly that config file changes take effect on startup.
Step 11: Keep MongoDB bound safely
By default, MongoDB binds to localhost. MongoDB’s documentation says mongod binds to 127.0.0.1 by default, which means local connections only. Remote clients cannot connect unless you change the binding.
If you need remote access, you can change the bind address in mongod.conf. MongoDB’s docs say you can use bindIp, 0.0.0.0, ::,0.0.0.0, or the net.bindIpAll setting / --bind_ip_all option.
Example configuration:
net:
bindIp: 127.0.0.1,192.168.1.50
port: 27017
Or, for broader binding:
net:
bindIpAll: trueMongoDB warns that before binding to a publicly accessible address, you should secure the deployment and harden the network. The docs specifically recommend at minimum enabling authentication and securing the network infrastructure.
Step 12: Create a database user and enable authentication
A fresh local install is often convenient during development, but production should not stay open without authentication. MongoDB’s documentation says that enabling access control enforces authentication, meaning users must identify themselves and can only perform actions allowed by their roles.
MongoDB also says each application or user should map to a distinct user account, following least privilege. To create users, you first need access control enabled and a user administrator account.
A common pattern is:
Connect locally.
Create an admin user.
Enable authentication in
mongod.conf.Restart MongoDB.
Reconnect using credentials. (MongoDB)
Here is an example admin-user creation flow:
use admin
db.createUser({
user: "admin",
pwd: passwordPrompt(),
roles: [
{ role: "userAdminAnyDatabase", db: "admin" },
{ role: "readWriteAnyDatabase", db: "admin" }
]
})
MongoDB’s db.createUser() documentation says this method creates a new user for the database where it is run, and that the userAdmin and userAdminAnyDatabase built-in roles provide the createUser and grantRole actions needed to manage users. The docs also note that passwordPrompt() is a supported way to enter the password interactively.
After creating the user, edit /etc/mongod.conf and enable authorization:
security:
authorization: enabled
MongoDB’s access-control documentation explains that enabling access control requires authentication and limits users to their granted permissions.
Then restart the service:
sudo systemctl restart mongod
Reconnecting now requires credentials:
mongosh --username admin --authenticationDatabase admin
MongoDB’s shell documentation shows exactly this pattern of using --username and --authenticationDatabase for authenticated connections. (MongoDB)
Step 13: Create an application database user
For real applications, create a separate user for each app instead of using the admin account. MongoDB recommends distinct users per application and least privilege. (MongoDB)
Example:
use appdb
db.createUser({
user: "appuser",
pwd: passwordPrompt(),
roles: [
{ role: "readWrite", db: "appdb" }
]
})
Then connect with that account:
mongosh "mongodb://localhost:27017/appdb" --username appuser --authenticationDatabase appdb
This style keeps the application isolated to the database it actually needs. MongoDB’s documentation on users and roles strongly supports this approach. (MongoDB)
Step 14: A clean example configuration for development
For a simple development machine where MongoDB stays local, this is a neat starting point:
storage:
dbPath: /var/lib/mongodb
systemLog:
destination: file
path: "/var/log/mongodb/mongod.log"
logAppend: true
net:
bindIp: 127.0.0.1
port: 27017
security:
authorization: enabled
That setup keeps the server local, logs to the standard package path, and turns on access control. MongoDB’s docs confirm these are the standard package locations and the default bind behavior for packaged installs.
After saving the file, restart the service:
sudo systemctl restart mongod
Then verify the status:
sudo systemctl status mongod
Step 15: Useful checks after installation
Once MongoDB is installed, a few checks help confirm everything is healthy:
mongosh
If that opens a shell, the database is reachable on the local machine with the default port. MongoDB’s shell docs say this is the expected local connection path. (MongoDB)
You can also check service and logs:
sudo systemctl status mongod
sudo tail -n 100 /var/log/mongodb/mongod.log
MongoDB’s docs specifically recommend checking the service status and the log file when troubleshooting.
Step 16: Common problems and how to think about them
1. mongod.service not found
MongoDB’s official docs say this usually means systemd has not reloaded the new service unit yet. Run:
sudo systemctl daemon-reload
sudo systemctl start mongod
This is the documented fix.
2. MongoDB starts but you cannot connect remotely
MongoDB binds to localhost by default, so remote clients cannot connect until you change bindIp or bindIpAll. MongoDB’s docs explicitly state that the default bind is 127.0.0.1.
3. The service fails after editing mongod.conf
MongoDB’s package docs note that the init scripts depend on key config values, and changes in the config file only take effect after restart. Check your YAML indentation carefully and restart the service. MongoDB warns that YAML does not support tabs.
4. Authentication is enabled but you cannot log in
Make sure you created the user in the correct database and that you are connecting with the matching --authenticationDatabase. MongoDB’s shell docs show that this option matters when authenticating.
5. You installed Ubuntu’s mongodb package by mistake
MongoDB says the Ubuntu package conflicts with the official mongodb-org package. Remove the conflicting package and install from MongoDB’s repository instead.
Step 17: How to uninstall MongoDB cleanly
MongoDB’s docs include an uninstall procedure that removes packages, configuration, logs, and data directories. The docs warn that this is destructive and irreversible unless you have backups.
Stop the server:
sudo service mongod stop
Remove the packages:
sudo apt-get purge mongodb-org*
Remove the data and log directories:
sudo rm -r /var/log/mongodb
sudo rm -r /var/lib/mongodb
That is the documented cleanup path for a full removal.
Step 18: A minimal production-minded checklist
When moving from a dev box to a real server, keep the following mindset:
Use the official MongoDB repository and packages.
Keep MongoDB bound to localhost unless remote access is truly required.
Enable authentication before exposing the server.
Create separate users for separate applications.
Monitor the logs after every change.
Restart
mongodafter editing the config.
MongoDB’s official docs support each of these ideas directly through their install, configuration, access-control, and shell guidance.
A quick end-to-end example
Here is the full flow in one place for a typical Ubuntu 24.04, 22.04, or 20.04 machine running MongoDB 8.0 Community Edition:
sudo apt-get update
sudo apt-get install gnupg curl
curl -fsSL https://pgp.mongodb.com/server-8.0.asc | \
sudo gpg -o /usr/share/keyrings/mongodb-server-8.0.gpg \
--dearmor
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
sudo apt-get update
sudo apt-get install -y mongodb-org
sudo systemctl start mongod
sudo systemctl enable mongod
sudo systemctl status mongod
mongosh
For Ubuntu 22.04 or 20.04, swap the repo codename in the echo line to jammy or focal, exactly as MongoDB’s Ubuntu install guide shows.
Final thoughts
Setting up MongoDB on Ubuntu is straightforward once you follow the official package path. The important ideas are simple: use MongoDB’s own repository, start the mongod service with systemctl, connect with mongosh, and secure the instance before exposing it to the network. MongoDB’s current Ubuntu docs and shell docs cover the full lifecycle, from installation and first connection to user creation, authentication, and cleanup.