12. Security and backups

You cannot ignore security and backups in production.

Security

MongoDB now requires authentication by default. If you use MongoDB Atlas, it is already configured.

If you installed MongoDB locally, you must:

  1. Create an administrator user
  2. Enable authentication
  3. Configure roles and permissions
  4. Use TLS/SSL for connections
  5. Limit access by IP

To create a user:

use admin

db.createUser({
    user: "admin",
    pwd: "your_secure_password",
    roles: [{ role: "userAdminAnyDatabase", db: "admin" }]
})

To create a database user:

use learn

db.createUser({
    user: "developer",
    pwd: "password",
    roles: [{ role: "readWrite", db: "learn" }]
})

Backups

There are several ways to make backups:

mongodump and mongorestore

These are tools that export/import data in BSON format:

# Backup of the entire database
mongodump -d learn -out backup

# Backup of a specific collection
mongodump -d learn -c unicorns -out backup

# Restore
mongorestore -d learn -c unicorns backup/learn/unicorns.bson

mongoexport and mongoimport

They export/import in JSON or CSV format:

# Export to JSON
mongoexport -d learn -c unicorns -o unicorns.json

# Export to CSV
mongoexport -d learn -c unicorns --csv --fields name,weight,vampires -o unicorns.csv

# Import from JSON
mongoimport -d learn -c unicorns --file unicorns.json

Important: use mongodump/mongorestore for real backups. They are more complete and preserve all data types. Use mongoexport/mongoimport only to export data to other systems.

Snapshots (recommended in production)

In production, the best option is disk-level snapshots. MongoDB Atlas does this automatically.

Best practices

  • Make regular backups (daily or more frequently)
  • Test your backups by restoring them
  • Store backups elsewhere (not on the same server)
  • Use replica sets for high availability
  • Monitor your database (memory, CPU, disk)
  • Keep MongoDB updated to the latest stable version
Building SPAs with Django and HTML Over the Wire: Learn to build real-time single page applications with Python

Building SPAs with Django and HTML Over the Wire: Learn to build real-time single page applications with Python

The HTML over WebSockets approach simplifies single-page application (SPA) development and lets you bypass learning a JavaScript rendering framework such as React, Vue, or Angular, moving the logic to Python. This web application development book provides you with all the Django tools you need to simplify your developments with real-time results.

Buy the book

Help me keep writing

Every coffee gives me a push toward the next article.

Comments

There are no comments yet.