Skip to content

Setting up a local MongoDB database

Share on
Updated

Overview

A local MongoDB server gives you a private place to learn the query language, try out schema ideas and run your application's tests without touching shared data. This guide installs MongoDB Community Server 9.0 and the MongoDB Shell, mongosh, on your computer, turns on authentication, and walks you through creating your first database.

The quickest route is Docker, which works the same on Linux, macOS and Windows. If you'd rather install MongoDB directly on your operating system, follow the section for your platform instead:

What you'll install

MongoDB publishes a major release every two years and supports each one for five years. MongoDB's lifecycle schedule lists these major releases as supported:

ReleaseReleasedEnd of life
MongoDB 9.0September 2026October 31, 2031
MongoDB 8.0October 2024October 31, 2029
MongoDB 7.0August 2023August 31, 2027

This guide uses 9.0, the newest one. If your production database runs 8.0 or 7.0, install the same release series locally so that you develop against the behavior you'll deploy on. MongoDB's installation guides have a version selector for each release. Since MongoDB 8.2 there are also minor releases between the major ones. The current one, 8.3 (May 2026), is listed as supported until October 31, 2029, the same date as 8.0. Unless you need a feature that only a minor release has, stick with a major release.

A working setup has up to four parts:

ComponentWhat it doesDo you need it?
MongoDB Community Server (mongod)The database server itselfYes
MongoDB Shell (mongosh)An interactive JavaScript shell for running commands and queries. It replaces the legacy mongo shell, which was deprecated in MongoDB 5.0 and removed in 6.0Yes
MongoDB Database ToolsCommand-line tools such as mongodump, mongorestore, mongoimport and mongoexportOptional. The Linux packages and Homebrew install them for you
MongoDB CompassA graphical interface for browsing and editing dataOptional

MongoDB Community Server doesn't include MongoDB Search and Vector Search. If you need them locally, MongoDB documents them as a separate installation.

Run MongoDB with Docker

Running MongoDB in a container keeps it separate from the rest of your system: one command starts it, the image tag pins the exact version, and removing it later leaves nothing behind. You need Docker (Docker Desktop on macOS and Windows, or Docker Engine on Linux).

MongoDB maintains its own image, mongodb/mongodb-community-server, and uses it in its Docker installation guide. (The mongo image on Docker Hub is a separate image maintained by the Docker community.) The image comes in several variants. Its Docker Hub page recommends the ubi9-slim variants, because the Ubuntu-based, UBI 8 and non-slim variants are being deprecated. The tag 9.0-ubi9-slim follows the latest 9.0 patch release. To pin an exact release, use a tag such as 9.0.2-ubi9-slim.

Start the server with a named volume for its data and an administrator account. The first line waits for you to type a password for the administrator and press Enter. It doesn't echo what you type, and the password doesn't end up in your shell history, as it would if you wrote it into the docker run command. The second line makes it available to docker run:

read -rs MONGO_INITDB_ROOT_PASSWORD
export MONGO_INITDB_ROOT_PASSWORD
docker run -d --name mongodb \
-p 127.0.0.1:27017:27017 \
-v mongodb-data:/data/db \
-e MONGO_INITDB_ROOT_USERNAME=admin \
-e MONGO_INITDB_ROOT_PASSWORD \
mongodb/mongodb-community-server:9.0-ubi9-slim

Each option has a job:

  • -p 127.0.0.1:27017:27017 publishes MongoDB's port on your computer's loopback interface only. Many examples, including MongoDB's own, use -p 27017:27017, which listens on every network interface of your computer, so anyone on the same network could reach the server.
  • -v mongodb-data:/data/db stores the database files in a Docker volume named mongodb-data. The data survives when you stop, restart or even delete the container.
  • MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD tell the image to create a user with the root role in the admin database the first time it starts with an empty volume, and to start mongod with authentication turned on. -e MONGO_INITDB_ROOT_PASSWORD without a value passes the variable from your shell. Anyone who can run docker inspect on your computer can still read the password, so don't reuse one from anywhere else.

Connect with the mongosh that ships inside the image. It asks for the password:

docker exec -it mongodb mongosh -u admin -p --authenticationDatabase admin

If you also install mongosh on your computer, the same command without the docker exec -it mongodb prefix connects through the published port.

To check that the server really requires a login, try to write without one:

docker exec mongodb mongosh --quiet --eval 'db.getSiblingDB("test").items.insertOne({ a: 1 })'
MongoServerError: Command insert requires authentication

Pass the two MONGO_INITDB_ROOT_* variables again whenever you re-create the container, for example to move to a newer 9.0 image. On a volume that already holds data, the image doesn't create the user again, but the variables are still what makes it start mongod with --auth. If you start a new container on the same volume without them, the users still exist but MongoDB no longer asks anyone to log in. If you'd rather not pass the password again, drop both variables and add --auth after the image name instead. Don't combine the two: with the variables set, an extra --auth makes mongod exit with Multiple occurrences of option "--auth".

Authentication is already on, so you can skip ahead to Create a database and your first document.

Install MongoDB on Linux

MongoDB publishes its own package repositories for Ubuntu, Debian and the RHEL family, and its Linux installation guide covers SUSE and Amazon Linux too. Install from these repositories rather than from your distribution: a package called mongodb from your distribution isn't maintained by MongoDB and conflicts with the official mongodb-org packages, so remove it first if you have one.

The mongodb-org package pulls in the server, mongosh and the Database Tools.

Ubuntu

MongoDB 9.0 supports Ubuntu 24.04 LTS ("Noble") and 22.04 LTS ("Jammy") on x86_64 and ARM64.

First, download MongoDB's signing key and store it as a keyring file:

sudo apt-get update
sudo apt-get install -y gnupg curl
curl -fsSL https://pgp.mongodb.com/server-9.asc | \
sudo gpg -o /usr/share/keyrings/mongodb-server-9.gpg --dearmor

Next, add the repository. The signed-by option ties the key to this one repository, so apt only accepts it for MongoDB's packages. The apt-key command that older guides use trusted a key for every repository, and it's deprecated. For Ubuntu 22.04, replace noble with jammy:

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

Then install MongoDB, start it, and have it start at boot:

sudo apt-get update
sudo apt-get install -y mongodb-org
sudo systemctl start mongod
sudo systemctl enable mongod

sudo systemctl status mongod shows whether the server is running. If it isn't, the log at /var/log/mongodb/mongod.log says why.

Debian

MongoDB 9.0 supports Debian 13 ("Trixie"), on x86_64 only; the repository has no ARM64 server packages for Debian. Import the key exactly as for Ubuntu, then add the Debian repository:

echo "deb [ signed-by=/usr/share/keyrings/mongodb-server-9.gpg ] https://repo.mongodb.org/apt/debian trixie/mongodb-org/9.0 main" | sudo tee /etc/apt/sources.list.d/mongodb-org-9.0.list

Install and start MongoDB with the same apt-get and systemctl commands as on Ubuntu.

RHEL, Rocky Linux, AlmaLinux and Oracle Linux

MongoDB 9.0 supports versions 8, 9 and 10 of RHEL, Rocky Linux and AlmaLinux on x86_64 and ARM64. On Oracle Linux, the platform support table lists only x86_64, and MongoDB supports it only with the Red Hat Compatible Kernel (RHCK), not the Unbreakable Enterprise Kernel (UEK). Create a repository definition. This one is for version 9; for the others, change the 9 after redhat/. $basearch is a dnf variable that becomes x86_64 or aarch64, and the quotes around 'EOF' keep your shell from expanding it:

sudo tee /etc/yum.repos.d/mongodb-org-9.0.repo <<'EOF'
[mongodb-org-9.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/9/mongodb-org/9.0/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://pgp.mongodb.com/server-9.asc
EOF

gpgcheck=1 makes dnf verify every package against MongoDB's key. The first time you install, dnf shows the key it imports:

sudo dnf install -y mongodb-org
Importing GPG key 0x602E502D:
Userid : "MongoDB 9 Release Signing Key <packaging@mongodb.com>"
Fingerprint: B3B4 2B6C 39E5 CDDE C0A2 7E3C F366 D55B 602E 502D
From : https://pgp.mongodb.com/server-9.asc
Key imported successfully

Start MongoDB and have it start at boot:

sudo systemctl start mongod
sudo systemctl enable mongod

If SELinux is enforcing on your system, read the SELinux section of MongoDB's installation guide. MongoDB provides a policy that works with the default paths, but not with custom data or log directories.

Running mongod without systemd

In a container or another environment without systemd, start mongod yourself as the service account the package created (mongodb on Ubuntu and Debian, mongod on the RHEL family), with the package's configuration file:

sudo -u mongodb mongod --config /etc/mongod.conf --fork

To stop it again, run the same command with --shutdown instead of --fork. Started this way, mongod may warn that the limit on open files is too low. The packaged systemd unit raises that limit to 64000, and MongoDB describes the recommended limits for starting it any other way.

Install MongoDB on macOS

MongoDB 9.0 supports macOS 14 or later, on Apple silicon and Intel Macs. MongoDB distributes it through its own Homebrew tap rather than Homebrew's main repository. These steps follow MongoDB's macOS installation guide; we couldn't run them on a Mac for this article.

If you don't have Homebrew yet, install it first. Then add the tap, mark it as trusted, and install MongoDB:

brew tap mongodb/brew
brew trust mongodb/brew
brew update
brew install mongodb-community@9.0

brew trust is needed because, since Homebrew 6.0.0, Homebrew only loads formulae from non-official taps that you have trusted. The formula also installs mongosh and the Database Tools. mongodb-community@9.0 is an alias for the tap's mongodb-community formula, so brew list and brew services list show it under that name.

Start MongoDB as a background service that also starts when you log in:

brew services start mongodb-community@9.0

brew services list shows mongodb-community as started. MongoDB notes that the open files limit might not be set when you start MongoDB through brew services, so you might need to set the ulimit values yourself. If macOS blocks mongod because it can't verify the developer, MongoDB's guide explains how to allow it in the Privacy & Security settings.

Install MongoDB on Windows

MongoDB 9.0 supports Windows 11 and Windows Server 2022 on x86_64. MongoDB doesn't support running it inside the Windows Subsystem for Linux (WSL); use the native installer or Docker instead. These steps follow MongoDB's Windows installation guide; we couldn't run them on Windows for this article.

  1. From the MongoDB Download Center, download the 9.0 release for Windows as an .msi package.
  2. Run the installer and choose the Complete setup type.
  3. Keep the option to install MongoDB as a Windows service, so that MongoDB runs in the background and starts as soon as the installation finishes. The default service account, the built-in Network Service account, is fine for local development. Note the data and log directories the installer shows, so that you can find your files later.
  4. Installing Compass is optional.
  5. The installer doesn't include mongosh. Install it separately and make sure its directory is on your PATH.

To stop and start the service, use the Services console, or run these commands in a terminal opened as Administrator:

net stop MongoDB
net start MongoDB

Turn on access control

This section is for the native installations above; the Docker container already requires a login.

A fresh MongoDB installation starts without access control. It only listens on localhost, but every program and every user account on your computer can read, change or delete every database without a password. And if you ever change that network binding, for example so that another machine or a container can connect, the whole server is open to your network. When you connect with mongosh, it warns you about this:

mongosh
The server generated these startup warnings when booting
2026-09-30T03:47:18.513+00:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted

Turning it on takes three steps.

1. Create an administrator. In mongosh, switch to the admin database and create a user. passwordPrompt() asks for the password, so it doesn't end up in your shell history:

use admin
db.createUser({
user: "admin",
pwd: passwordPrompt(),
roles: [
{ role: "userAdminAnyDatabase", db: "admin" },
{ role: "readWriteAnyDatabase", db: "admin" }
]
})
{ ok: 1 }

These are the roles MongoDB's SCRAM authentication tutorial uses: userAdminAnyDatabase manages users and roles, and readWriteAnyDatabase reads and writes data in every database. The Docker image gives its first user the broader root role instead. Type exit to leave mongosh.

2. Enable authorization in the configuration file. Open the configuration file for your platform in an editor with administrator rights:

PlatformConfiguration file
Linux/etc/mongod.conf
macOS (Homebrew)/opt/homebrew/etc/mongod.conf on Apple silicon, /usr/local/etc/mongod.conf on Intel
WindowsC:\Program Files\MongoDB\Server\9.0\bin\mongod.cfg

On Linux, the packaged file contains a commented-out #security: line. Replace it with this block, or add the block if your file has no such line:

security:
authorization: enabled

The file is YAML, so indent authorization with spaces, not a tab.

3. Restart MongoDB so that it reads the new setting:

PlatformCommand
Linuxsudo systemctl restart mongod
macOS (Homebrew)brew services restart mongodb-community@9.0
Windowsnet stop MongoDB, then net start MongoDB (as Administrator)

Connections without a login still succeed, but they can't read or change data anymore:

mongosh --quiet --eval 'db.getSiblingDB("test").items.insertOne({ a: 1 })'
MongoServerError: Command insert requires authentication

From now on, connect as the administrator and type the password when mongosh asks for it:

mongosh -u admin -p --authenticationDatabase admin

The --authenticationDatabase admin option tells MongoDB where the user is defined. If you turn on authorization before creating any user, MongoDB's localhost exception still lets you create the first user from the same machine.

Create a database and your first document

Use the administrator account for administration only, and give each application its own user that can only work with its own database.

If you run MongoDB in Docker and haven't installed mongosh on your computer, put docker exec -it mongodb in front of each mongosh command in this section, for example docker exec -it mongodb mongosh -u admin -p --authenticationDatabase admin.

Connect as the administrator:

mongosh -u admin -p --authenticationDatabase admin

Then create a user for a bookstore database:

use bookstore
db.createUser({
user: "bookstore_app",
pwd: passwordPrompt(),
roles: [ { role: "readWrite", db: "bookstore" } ]
})

use bookstore switches to the database even though it doesn't exist yet. MongoDB creates databases and collections the first time you store data in them. The user belongs to bookstore, which is its authentication database, and the readWrite role only applies to that database.

Exit and connect again as the new user. Because the connection string names a user but no password, mongosh asks for the password:

mongosh "mongodb://bookstore_app@127.0.0.1:27017/bookstore"

Insert a document into a books collection and read it back:

db.books.insertOne({ title: 'Dune', author: 'Frank Herbert', year: 1965 })
db.books.find()
{
acknowledged: true,
insertedId: ObjectId('6abc88a44084dbe033284d0c')
}
[
{
_id: ObjectId('6abc88a44084dbe033284d0c'),
title: 'Dune',
author: 'Frank Herbert',
year: 1965
}
]

MongoDB created the bookstore database and the books collection when the first document arrived, and added a unique _id because the document didn't have one. Your application connects with the same kind of connection URI, with the password included: mongodb://bookstore_app:<password>@127.0.0.1:27017/bookstore.

Where MongoDB keeps its files

InstallationConfigurationDataLog
DockerOptions on the docker run commandThe mongodb-data volume (/data/db inside the container)docker logs mongodb
Ubuntu and Debian/etc/mongod.conf/var/lib/mongodb/var/log/mongodb/mongod.log
RHEL family/etc/mongod.conf/var/lib/mongo/var/log/mongodb/mongod.log
macOS (Homebrew)$(brew --prefix)/etc/mongod.conf$(brew --prefix)/var/mongodb$(brew --prefix)/var/log/mongodb/mongo.log
WindowsC:\Program Files\MongoDB\Server\9.0\bin\mongod.cfgChosen in the installerChosen in the installer

brew --prefix is /opt/homebrew on Apple silicon Macs and /usr/local on Intel Macs. On Linux, the server runs as the mongodb user (Ubuntu and Debian) or the mongod user (RHEL family), which owns the data and log directories. MongoDB reads its configuration file only at startup, so restart it after every change. The configuration file options reference lists every setting.

To start, stop and restart the server:

InstallationStartStopRestart
Dockerdocker start mongodbdocker stop mongodbdocker restart mongodb
Linuxsudo systemctl start mongodsudo systemctl stop mongodsudo systemctl restart mongod
macOSbrew services start mongodb-community@9.0brew services stop mongodb-community@9.0brew services restart mongodb-community@9.0
Windowsnet start MongoDBnet stop MongoDBStop, then start

Remove MongoDB

Removing MongoDB's data directory deletes every database in it, and there's no undo. If you want to keep anything, back it up first with mongodump.

Docker: remove the container, the volume that holds the data, and the image:

docker rm -f mongodb
docker volume rm mongodb-data
docker image rm mongodb/mongodb-community-server:9.0-ubi9-slim

Ubuntu and Debian: name mongosh and the Database Tools explicitly, because mongodb-org* alone leaves them installed:

sudo systemctl stop mongod
sudo apt-get purge -y "mongodb-org*" mongodb-mongosh mongodb-database-tools
sudo rm -r /var/lib/mongodb /var/log/mongodb
sudo rm /etc/apt/sources.list.d/mongodb-org-9.0.list /usr/share/keyrings/mongodb-server-9.gpg

RHEL family:

sudo systemctl stop mongod
sudo dnf remove -y "mongodb-org*" mongodb-mongosh mongodb-database-tools
sudo rm -r /var/lib/mongo /var/log/mongodb
sudo rm /etc/yum.repos.d/mongodb-org-9.0.repo

If you edited /etc/mongod.conf, dnf keeps your version as /etc/mongod.conf.rpmsave. Delete it too if you don't need it.

macOS: stop the service, uninstall the formulae (brew list shows what's installed), and delete the data, log and configuration files listed in the table above. brew untap mongodb/brew removes the tap, and brew untrust mongodb/brew withdraws the trust you granted it.

Windows: uninstall MongoDB, and mongosh and Compass if you installed them, the way you remove any other Windows program. Then delete the data and log directories you chose during installation.

Next steps

A hosted Postgres database for your next project, with connection pooling and backups built in. Explore Prisma Postgres →