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

This work is under a Attribution-NonCommercial-NoDerivatives 4.0 International license.

Desafíos de programación atemporales y multiparadigmáticos

Desafíos de programación atemporales y multiparadigmáticos

Te encuentras ante un librillo de actividades, divididas en 2 niveles de dificultad. Te enfrentarás a los casos más comunes que te puedes encontrar en pruebas técnicas o aprender conceptos elementales de programación.

Buy the book

Will you buy me a coffee?

This is how I keep writing without ads or paywalls.

Comments

There are no comments yet.