Dit deel is nog niet vertaald. Je ziet de Engelse tekst.
$ als gewone gebruiker# als root (of met sudo)
Know it before you install
A server holds databases, a database holds collections, a collection holds documents. Users live in a database (usually admin) and get roles (readWrite on one database, userAdminAnyDatabase …). A replica set is 3 servers with the same data: one primary, two secondaries.
| Item | Value |
|---|---|
| Packages | mongodb-org (server mongod, shell mongosh, tools mongodump/mongorestore) |
| Service | mongod.service |
| Config | /etc/mongod.conf (YAML) |
| Data | /var/lib/mongo (RHEL), /var/lib/mongodb (Ubuntu) |
| Log | /var/log/mongodb/mongod.log |
| Port | 27017/tcp |
Let op
Without security.authorization: enabled, anyone who can reach port 27017 can read and delete everything. Thousands of open MongoDB servers have been wiped and held for ransom.
Install on RHEL, Rocky and Alma
Use the repository for your RHEL major version (here 9):
cat > /etc/yum.repos.d/mongodb-org-8.0.repo <<'EOF'
[mongodb-org-8.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/9/mongodb-org/8.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://pgp.mongodb.com/server-8.0.asc
EOF
dnf -y install mongodb-org
systemctl enable --now mongodWith SELinux enforcing, follow MongoDB's SELinux steps (the mongodb-selinux policy) if mongod is blocked — check with ausearch -m avc -ts recent.
Install on Ubuntu and Debian
For Ubuntu 24.04 (noble; use jammy for 22.04):
apt-get install -y gnupg curl
curl -fsSL https://pgp.mongodb.com/server-8.0.asc | 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" > /etc/apt/sources.list.d/mongodb-org-8.0.list
apt-get update
apt-get install -y mongodb-org
systemctl enable --now mongod
mongosh --eval 'db.runCommand({ ping: 1 })'
{ ok: 1 }First steps: an admin user, then turn on authentication
While it still listens only on localhost, create the first admin:
use admin
db.createUser({
user: "admin",
pwd: passwordPrompt(),
roles: [ { role: "userAdminAnyDatabase", db: "admin" }, { role: "readWriteAnyDatabase", db: "admin" } ]
})Now turn on authentication and set the network in the config:
storage:
dbPath: /var/lib/mongo
systemLog:
destination: file
path: /var/log/mongodb/mongod.log
logAppend: true
net:
port: 27017
bindIp: 127.0.0.1,10.0.2.21
security:
authorization: enabled
processManagement:
timeZoneInfo: /usr/share/zoneinfo(On Ubuntu dbPath is /var/lib/mongodb.)
Create a user for the app with rights only on its database:
use shop
db.createUser({ user: "shop", pwd: passwordPrompt(), roles: [ { role: "readWrite", db: "shop" } ] })The app connects with mongodb://shop:PASSWORD@10.0.2.21:27017/shop?authSource=shop.
| Setting | Why |
|---|---|
security.authorization: enabled | Every client must log in; roles decide what it may do. |
net.bindIp | Listen only on localhost and the private IP — never 0.0.0.0 on a public server. |
| One user per app | readWrite on its own database only. |
Open the firewall only for the app servers:
firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="10.0.1.0/24" port port="27017" protocol="tcp" accept'
firewall-cmd --reloadReplica set (production)
For real data run 3 servers. On each: the same replication.replSetName and a shared keyFile (members authenticate to each other):
openssl rand -base64 756 > /etc/mongod.key
chmod 400 /etc/mongod.key && chown mongod: /etc/mongod.keyreplication:
replSetName: rs0
security:
authorization: enabled
keyFile: /etc/mongod.keyCopy the same key file to all 3 nodes, restart, then once on one node:
rs.initiate({ _id: "rs0", members: [
{ _id: 0, host: "mongo1.example.com:27017" },
{ _id: 1, host: "mongo2.example.com:27017" },
{ _id: 2, host: "mongo3.example.com:27017" } ] })
rs.status()(The user on Ubuntu is mongodb, not mongod.)
Daily use: the commands and the real uses
show dbs
use shop
show collections
db.orders.find({ status: "open" }).limit(5)
db.orders.countDocuments()
db.orders.createIndex({ customerId: 1, createdAt: -1 })
db.orders.find({ customerId: 42 }).explain("executionStats")
db.currentOp({ secs_running: { $gt: 5 } })
db.stats()
db.serverStatus().connectionsBackups (logical) and restore:
mongodump --uri="mongodb://admin@127.0.0.1:27017/?authSource=admin" --gzip --archive=/backup/mongo-$(date +%F).gz
mongorestore --uri="mongodb://admin@127.0.0.1:27017/?authSource=admin" --gzip --archive=/backup/mongo-2026-11-16.gz --nsInclude='shop.*' --dropReal uses at work:
- Databases for apps with flexible data (catalogs, user profiles, events, CMS).
- Replica sets for high availability; indexes and
explainfor slow queries. - Many teams use MongoDB Atlas (cloud) — the same
mongoshcommands work there.
Make it safe
Security checklist:
authorization: enabledalways; strong passwords; one user per app with least privilege.bindIpon localhost + private IP; firewall 27017 to app servers only; never public.- TLS (
net.tls.mode: requireTLS) when traffic crosses networks. - Replica sets with a keyFile (or x.509) for member authentication.
- Encrypted backups in another place, with restore tests.
- Keep MongoDB updated within its major version; read the production notes (ulimits, file system XFS).
Update and remove
Major upgrades (7.0 → 8.0) go one major version at a time, after setting featureCompatibilityVersion — read the upgrade notes, back up first. Remove: dnf remove mongodb-org* / apt-get purge mongodb-org* (the data folder stays).
Fix common problems
| Problem | Cause | Fix |
|---|---|---|
MongoServerError: Authentication failed | Wrong password or wrong authSource. | Use the database where the user was created: --authenticationDatabase admin / ?authSource=…. |
ECONNREFUSED from another server | bindIp is localhost only, or firewall. | Add the private IP to bindIp; open 27017 for the app subnet. |
mongod does not start | Wrong owner of the data folder, old lock file, YAML error. | journalctl -u mongod; tail /var/log/mongodb/mongod.log; chown -R mongod: /var/lib/mongo. |
not authorized on shop to execute command | The user has no role for that database. | db.grantRolesToUser(...) with the right role. |
Replica set: No host described in new configuration … for replica set rs0 maps to this node | Host names do not resolve to this server. | Fix DNS or /etc/hosts; use names that every node can resolve. |
| Slow queries | Missing index. | explain("executionStats") — look for COLLSCAN; create an index. |
| Disk full | Data growth or logs. | Delete old data, add disk; log rotation (systemLog.logRotate). |
Next steps
- Command page: mongosh.
- At work: Document database.
- The other databases: PostgreSQL, MySQL / MariaDB, Redis.
1What is the most dangerous default of MongoDB?
Authentication is off. Anyone who reaches port 27017 can read and delete all data.
2The app user exists in database shop, but login fails with authSource=admin. Why?
The user lives in shop, so the app must use authSource=shop.