Backup and Monitoring

Protect and run MongoDB in production: back up with mongodump, snapshots and Atlas continuous backup, restore and test recovery, export data, monitor key metrics such as connections, operation latency, replication lag and disk, read serverStatus and currentOp, and set useful alerts.

Lesson 25 of 43Advanced17 min read

Hardware fails, people run the wrong command, software has bugs, and attackers delete data. Replication protects against a server failing, but not against mistakes: a deleteMany({}) on the primary is copied to every secondary within milliseconds. Only backups let you go back in time, and only tested backups are worth having. Many teams discover their backups don't work on the day they need them.

Backups come in a few forms. Logical backups with mongodump export data as BSON files you can restore anywhere. Snapshots copy the database's files at the storage level, which is much faster for large deployments. Continuous backup in Atlas records every change, allowing point-in-time restore to any second within the retention window.

Running a database well also means monitoring it: watching connections, operation latency, replication lag, memory, disk space and slow queries, and getting alerts before users notice problems. In this lesson you'll back up and restore with the database tools, export and import data, read the server's own diagnostics, and set up a practical list of metrics and alerts.

Backups with mongodump and mongorestore

Terminal
mongodump --uri "$MONGODB_URI" --gzip --archive=shop-2026-03-01.gz --db shop
mongorestore --uri "$RESTORE_URI" --gzip --archive=shop-2026-03-01.gz --nsInclude "shop.*"
mongorestore --uri "$RESTORE_URI" --gzip --archive=shop-2026-03-01.gz --nsFrom "shop.*" --nsTo "shop_restored.*"
  • mongodump writes collections, indexes definitions and metadata; --gzip --archive produces one compressed file.
  • mongorestore loads a dump; --nsInclude restores only some collections, and --nsFrom/--nsTo restores into a different name, so you can recover one collection without overwriting live data.
  • Use --oplog with dumps of a replica set for a consistent point in time.
  • Logical dumps suit small and medium databases; large ones use snapshots or Atlas continuous backup.

Export, import and backup strategy

  • mongoexport and mongoimport move data as JSON or CSV, for spreadsheets, other systems or seeding test data. They aren't full backups, because types such as dates and decimals can be lost in CSV.
  • Decide your RPO (how much data you can afford to lose, such as 5 minutes) and RTO (how quickly you must be back, such as 1 hour). They determine how often you back up and which method you use.
  • Store backups off-site and encrypted, keep several generations, and restore regularly into a test environment to prove they work.

Monitoring the server

MongoDB Shell
db.serverStatus().connections          // current and available connections
db.serverStatus().opcounters           // inserts, queries, updates and deletes so far
db.stats()                             // data and index size for the database
db.currentOp({ secs_running: { $gte: 5 } })   // operations running for 5+ seconds
db.killOp(opid)                        // stop a runaway operation
rs.printSecondaryReplicationInfo()     // replication lag

Command-line tools mongostat and mongotop show live activity and time spent per collection. Atlas, Ops Manager and tools such as Prometheus with Grafana or Datadog chart these metrics over time and send alerts.

MongoDB Operations Syntax

Operations toolbox

mongodump --uri "$URI" --db shop --gzip --archive=shop.gz
mongorestore --uri "$URI" --gzip --archive=shop.gz --nsInclude "shop.orders"
mongoexport --uri "$URI" --collection orders --type=csv --fields _id,total,status --out orders.csv
mongoimport --uri "$URI" --collection products --file products.json --jsonArray
mongostat --uri "$URI" 5
mongotop --uri "$URI" 10
db.serverStatus().connections
db.currentOp({ active: true, secs_running: { $gte: 10 } })
db.stats(1024 * 1024)

MongoDB Operations Summary

  • Replication doesn't protect against mistakes; only backups let you go back in time.
  • mongodump and mongorestore make logical backups; snapshots and Atlas continuous backup suit large data.
  • Restore into a different namespace to recover selectively, and test restores regularly.
  • serverStatus, stats, currentOp, mongostat and mongotop show what the server is doing.
  • Monitor connections, latency, replication lag, memory, disk and slow queries, with a few actionable alerts.

MongoDB Operations Examples

Each example shows the code, the output it produces and what each part does.

Example 1

A backup and selective restore

Terminal
mongodump --uri "mongodb://backup:...@db1:27017/?authSource=admin" --db shop --gzip --archive=shop-2026-03-01.gz
mongorestore --uri "mongodb://restore:...@staging:27017/?authSource=admin" --gzip --archive=shop-2026-03-01.gz --nsInclude "shop.orders" --nsFrom "shop.orders" --nsTo "recovery.orders"
Output
2026-03-01T02:00:01.120+0000    writing shop.orders to archive 'shop-2026-03-01.gz'
2026-03-01T02:00:01.121+0000    writing shop.products to archive 'shop-2026-03-01.gz'
2026-03-01T02:00:04.388+0000    done dumping shop.products (1840 documents)
2026-03-01T02:00:09.902+0000    done dumping shop.orders (412337 documents)
2026-03-01T09:15:22.415+0000    restoring recovery.orders from archive 'shop-2026-03-01.gz'
2026-03-01T09:15:41.006+0000    finished restoring recovery.orders (412337 documents, 0 failures)
2026-03-01T09:15:41.006+0000    412337 document(s) restored successfully. 0 document(s) failed to restore.
Line-by-line explanation
  1. Line 1A dedicated backup user dumps the shop database into one compressed archive file.
  2. Line 2Only the orders collection is restored, into a separate recovery database on a staging server.
  3. Line 2Restoring alongside live data lets you compare and copy back just the records that were lost.
Example 2

Checking server health

MongoDB Shell
const s = db.serverStatus()
s.connections.current < s.connections.available
Object.keys(s.opcounters)
const stats = db.stats(1024 * 1024)
`${stats.collections} collections, ${stats.dataSize.toFixed(1)} MB data, ${stats.indexSize.toFixed(1)} MB indexes`
db.currentOp({ secs_running: { $gte: 30 } }).inprog.length
Output
true
[ 'insert', 'query', 'update', 'delete', 'getmore', 'command' ]
14 collections, 2380.4 MB data, 412.7 MB indexes
0
Line-by-line explanation
  1. Line 2Plenty of connections are still available; running out causes errors for new requests.
  2. Line 3opcounters track every kind of operation since the server started; monitoring tools graph their rate.
  3. Line 4db.stats with a scale of 1024 * 1024 reports sizes in megabytes.
  4. Line 6No operation has been running for 30 seconds or more; long ones often mean a missing index.
Example 3

Exporting and importing data

Terminal
mongoexport --uri "$URI" --db shop --collection products --query '{"category":"kitchen"}' --type=csv --fields name,price --out kitchen.csv
head -3 kitchen.csv
mongoimport --uri "$STAGING_URI" --db shop --collection products --type=csv --headerline --file kitchen.csv
Output
2026-03-01T10:02:11.511+0000    connected to: mongodb://[**REDACTED**]@db1:27017
2026-03-01T10:02:11.538+0000    exported 2 records
name,price
Mug,8.5
Kettle,29.99
2026-03-01T10:02:15.880+0000    connected to: mongodb://[**REDACTED**]@staging:27017
2026-03-01T10:02:15.912+0000    2 document(s) imported successfully. 0 document(s) failed to import.
Line-by-line explanation
  1. Line 1mongoexport writes matching documents as CSV with just the chosen fields, ready for a spreadsheet.
  2. Line 2The file has a header row and one line per product.
  3. Line 3mongoimport loads it into another environment, using the header row for field names.
  4. Line 3CSV loses types such as dates and decimals, so use mongodump for real backups.

Common MongoDB Operations Mistakes

Treating replication as a backup

Don't
// "we have three replicas, so we don't need backups"
db.orders.deleteMany({})              // deleted on every replica within milliseconds
Do
// scheduled backups or continuous backup with point-in-time restore, stored separately

Never testing restores

Don't
mongodump ... --archive=nightly.gz    # runs every night for a year; nobody has tried restoring it
Do
mongorestore --uri "$TEST_URI" --gzip --archive=nightly.gz --dryRun   # and a full test restore every month

Restoring over live data

Don't
mongorestore --uri "$PROD_URI" --drop --archive=old.gz   # replaces today's data with last week's
Do
mongorestore --uri "$PROD_URI" --archive=old.gz --nsFrom "shop.*" --nsTo "recovery.*"

MongoDB Operations in Real Projects

Operations in practice

Atlas customers turn on continuous backup with point-in-time restore and test restores into a separate project. Self-managed teams combine nightly snapshots with oplog backups, store copies in another region, and monitor with Prometheus exporters and Grafana dashboards. On-call engineers follow runbooks for alerts such as high replication lag or full disks, and every incident review asks whether monitoring could have warned earlier.

MongoDB Operations FAQ

What is the difference between mongodump and mongoexport?

mongodump writes BSON, keeping every type exactly, plus index definitions and collection options, and is meant for backups restored with mongorestore. mongoexport writes JSON or CSV for use in other tools, and CSV in particular loses type information. Use mongodump for backups and mongoexport for sharing data.

How do I check the size of a MongoDB database?

Run db.stats() in mongosh. It reports dataSize, storageSize and indexSize in bytes, and passing a scale such as db.stats(1024 * 1024) shows them in megabytes. For one collection, db.orders.stats() gives the same figures, and show dbs lists every database's size on disk.

Does mongodump lock the database or stop the application?

No. mongodump reads through normal queries while the application keeps working. It does add read load and can push frequently used data out of memory, so run it against a secondary or during quieter hours on busy systems. Without --oplog, writes that happen during the dump can leave it slightly inconsistent between collections.

How do I restore a single collection from a mongodump backup?

Use --nsInclude with the full namespace: mongorestore --gzip --archive=shop.gz --nsInclude 'shop.orders'. To avoid overwriting live data, combine it with --nsFrom 'shop.orders' --nsTo 'shop.orders_restored' and copy back only what you need. Add --drop only when you deliberately want to replace the existing collection.

How do I see how many connections MongoDB has open?

Run db.serverStatus().connections, which shows current, available and totalCreated. A steady climb in current usually means an application is creating new clients instead of reusing one. db.currentOp() lists what those connections are doing right now.

MongoDB Operations Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Fill in the blankseasy

Complete the command that makes a compressed logical backup.

 --uri "$URI" --db shop --gzip --archive=shop.gz
Multiple choiceeasy

Does a replica set protect you from accidentally deleting data?

Multiple choicemedium

Which tool restores a mongodump archive?

Multiple choicemedium

What does RPO describe?

Multiple choicehard

How can you recover one collection without overwriting live data?

MongoDB Operations Quiz

5 questions to check what you learned.

  1. Which command lists operations currently running on the server?

    • db.stats()
    • db.currentOp()
    • db.getUsers()
    • rs.conf()
  2. Why isn't mongoexport to CSV a full backup?

    • CSV loses BSON types such as dates and decimals, and indexes aren't included
    • It's too slow
    • It can't export large collections
    • It requires Atlas
  3. What does point-in-time restore allow?

    • Restoring only today's data
    • Restoring indexes only
    • Restoring the database to its state at any moment within the retention window
    • Undoing a single query instantly
  4. Which metric warns that secondaries are falling behind?

    • Connections
    • Replication lag
    • Index size
    • opcounters
  5. What makes an alert useful?

    • It fires often
    • It covers every metric
    • It only emails managers
    • It's actionable, signals a real symptom, and comes with steps to investigate