DeveloperBootstrap

Databases

MongoDB Enterprise Guide

Deploy MongoDB enterprise clusters with replica sets, sharding, security hardening, and performance tuning on Ubuntu 24.04 LTS.

What you'll learn

  • Install and configure MongoDB 7 for production
  • Set up a 3-node replica set for high availability
  • Configure sharding for horizontal scaling
  • Implement authentication and role-based access control
  • Design optimal indexes for your query patterns
  • Monitor with MongoDB Atlas or self-hosted tools
  • Perform backup and restore with mongodump and Atlas backups

Installation

Bash
1# Install MongoDB 7 on Ubuntu 24.04
2curl -fsSL https://www.mongodb.org/static/pgp/server-7.0.asc |   sudo gpg --dearmor -o /etc/apt/keyrings/mongodb-server-7.0.gpg
3echo "deb [ signed-by=/etc/apt/keyrings/mongodb-server-7.0.gpg ]   https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" |   sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
4sudo apt update && sudo apt install -y mongodb-org
5sudo systemctl enable --now mongod
6
7# Verify
8mongosh --eval "db.runCommand({ connectionStatus: 1 })"

Replica Set Setup

JavaScript
1# /etc/mongod.conf — on all 3 nodes
2replication:
3  replSetName: "rs0"
4
5net:
6  bindIp: 0.0.0.0
7  port: 27017
8
9# Initiate replica set (on primary candidate)
10mongosh
11rs.initiate({
12  _id: "rs0",
13  members: [
14    { _id: 0, host: "mongo1:27017", priority: 2 },
15    { _id: 1, host: "mongo2:27017", priority: 1 },
16    { _id: 2, host: "mongo3:27017", priority: 1 }
17  ]
18})
19
20# Check status
21rs.status()
22rs.isMaster()

Sharding

JavaScript
1# Enable sharding on a database
2use admin
3sh.enableSharding("mydb")
4
5# Shard a collection on hashed _id (even distribution)
6sh.shardCollection("mydb.events", { _id: "hashed" })
7
8# Shard on a range key (locality — useful for time-series)
9sh.shardCollection("mydb.orders", { userId: 1, createdAt: 1 })
10
11# Check shard distribution
12db.orders.getShardDistribution()

Security & RBAC

JavaScript
1# Enable authentication in mongod.conf
2security:
3  authorization: enabled
4  keyFile: /etc/mongodb/keyfile   # for replica set internal auth
5
6# Create admin user first
7use admin
8db.createUser({
9  user: "admin",
10  pwd: passwordPrompt(),
11  roles: ["userAdminAnyDatabase", "dbAdminAnyDatabase", "clusterAdmin"]
12})
13
14# Create app user with least privilege
15use mydb
16db.createUser({
17  user: "appuser",
18  pwd: "securepassword",
19  roles: [
20    { role: "readWrite", db: "mydb" }
21  ]
22})

Indexing

JavaScript
1// ESR rule: Equality → Sort → Range
2db.orders.createIndex({ userId: 1, status: 1, createdAt: -1 })
3
4// Text search index
5db.courses.createIndex({ title: "text", description: "text" })
6db.courses.find({ $text: { $search: "typescript react" } })
7
8// Wildcard index (flexible schema)
9db.products.createIndex({ "attributes.$**": 1 })
10
11// Find slow queries and missing indexes
12db.setProfilingLevel(1, { slowms: 100 })
13db.system.profile.find({}, { op: 1, ns: 1, millis: 1 }).sort({ millis: -1 }).limit(5)
14
15// Drop unused index
16db.orders.dropIndex("old_index_name")

Backup & Recovery

Bash
1# Logical backup with mongodump
2mongodump --uri="mongodb://appuser:pass@localhost:27017/mydb"   --out=/backups/mydb_$(date +%Y%m%d)
3
4# Restore
5mongorestore --uri="mongodb://appuser:pass@localhost:27017/mydb"   /backups/mydb_20250918/mydb/
6
7# Backup from secondary to avoid impacting primary
8mongodump --uri="mongodb://appuser:pass@mongo2:27017/mydb?readPreference=secondary"

Monitoring

Bash
1# Real-time server stats
2mongotop --uri="mongodb://admin:pass@localhost:27017"
3mongostat --uri="mongodb://admin:pass@localhost:27017"
4
5# Key metrics to watch
6db.serverStatus().connections    # current, available, totalCreated
7db.serverStatus().opcounters     # insert, query, update, delete rates
8db.serverStatus().wiredTiger.cache["pages read into cache"]
9
10# Prometheus exporter
11docker run -d --name mongodb_exporter   -e MONGODB_URI="mongodb://admin:pass@localhost:27017"   -p 9216:9216 percona/mongodb_exporter:latest