متقدم
البحث فيأدلة التثبيت
طريقة البحث
  • الصق رسالة الخطأ بين علامتي تنصيص، مثل "permission denied"، لتجد جدول الحل.
  • اختر مجالًا وجزءًا من الدليل (التثبيت، أول الإعدادات، الاستخدام اليومي، الأمان، الحلول) لتصل مباشرة إلى الخطوة الصحيحة.
  • "كلمتان" تجد العبارة بالضبط.
  • الكلمات العادية تجد الأسماء والنصوص والأمثلة.
  • ↑ ↓ للتنقل · Enter للفتح · Esc للإغلاق · / للبحث
جرّب:

الدليل 44MongoDB · Data

Install and set up MongoDB

MongoDB is the most used document database: it stores JSON-like documents, so apps can save flexible data without fixed tables. As an engineer you install it, turn on authentication (it is off by default!), bind it to the right network, create users with the right roles, run a replica set for safety, and make backups. This guide does all of that on RHEL and Ubuntu with the official MongoDB 8.0 packages.

  • 10 الدروس
  • 15 الأوامر

هذا الجزء لم يُترجم بعد. أنت ترى النص الإنجليزي.

$ مستخدم عادي# بصلاحية root (أو مع sudo)

44.1

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.

ItemValue
Packagesmongodb-org (server mongod, shell mongosh, tools mongodump/mongorestore)
Servicemongod.service
Config/etc/mongod.conf (YAML)
Data/var/lib/mongo (RHEL), /var/lib/mongodb (Ubuntu)
Log/var/log/mongodb/mongod.log
Port27017/tcp

انتبه

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.

الأوامر في هذا الدرس

44.2

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 mongod

With SELinux enforcing, follow MongoDB's SELinux steps (the mongodb-selinux policy) if mongod is blocked — check with ausearch -m avc -ts recent.

44.3

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 }

44.4

First steps: an admin user, then turn on authentication

While it still listens only on localhost, create the first admin:

mongosh
mongosh
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:

/etc/mongod.conf
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.)

systemctl restart mongod
mongosh -u admin -p --authenticationDatabase admin

Create a user for the app with rights only on its database:

mongosh
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.

SettingWhy
security.authorization: enabledEvery client must log in; roles decide what it may do.
net.bindIpListen only on localhost and the private IP — never 0.0.0.0 on a public server.
One user per appreadWrite 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 --reload

44.5

Replica 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.key
/etc/mongod.conf (add)
replication:
  replSetName: rs0
security:
  authorization: enabled
  keyFile: /etc/mongod.key

Copy the same key file to all 3 nodes, restart, then once on one node:

mongosh
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.)

44.6

Daily use: the commands and the real uses

mongosh
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().connections

Backups (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.*' --drop

Real uses at work:

  • Databases for apps with flexible data (catalogs, user profiles, events, CMS).
  • Replica sets for high availability; indexes and explain for slow queries.
  • Many teams use MongoDB Atlas (cloud) — the same mongosh commands work there.

44.7

Make it safe

Security checklist:

  • authorization: enabled always; strong passwords; one user per app with least privilege.
  • bindIp on 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).

44.8

Update and remove

dnf -y upgrade mongodb-org
apt-get install --only-upgrade -y mongodb-org
systemctl restart mongod

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).

44.9

Fix common problems

ProblemCauseFix
MongoServerError: Authentication failedWrong password or wrong authSource.Use the database where the user was created: --authenticationDatabase admin / ?authSource=….
ECONNREFUSED from another serverbindIp is localhost only, or firewall.Add the private IP to bindIp; open 27017 for the app subnet.
mongod does not startWrong 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 commandThe 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 nodeHost names do not resolve to this server.Fix DNS or /etc/hosts; use names that every node can resolve.
Slow queriesMissing index.explain("executionStats") — look for COLLSCAN; create an index.
Disk fullData growth or logs.Delete old data, add disk; log rotation (systemLog.logRotate).

44.10

Next steps

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.

الأوامر في هذا الدرس

كل الأوامر في هذا الفصل