1. Core Concepts
MongoDB is a distributed, document-oriented NoSQL database system written in C++. It stores data in flexible, JSON-like documents where data structures consist of key-value pairs. This design allows for dynamic schemas, making it highly adaptable to evolving application requirements.
2. Comparison: Relational vs. Document
While relational databases like MySQL use rows and tables, MongoDB uses documents and collections. The mapping is as follows:
- Database: Both systems share this concept.
- Table (MySQL) vs. Collection (MongoDB): MongoDB organizes documents into collections.
- Row (MySQL) vs. Document (MongoDB): Data is represented as a self-contained object in MongoDB.
- Column (MySQL) vs. Field (MongoDB): MongoDB uses fields to store specific key-value pairs.
3. Use Cases
- Content Management: Storing articles with varying metadata.
- Log Aggregation: Handling high-volume, unstructured log data from IoT devices.
- E-commerce: Managing product catalogs where items have highly heterogeneous attributes.
- Gaming: Storing player profiles, inventories, and scores within nested documents.
4. Deployment and Configuration
To deploy a production-ready MongoDB instance, observe the following best practices:
- Disable Transparent Huge Pages (THP) and ensure proper memory limits in
/etc/security/limits.conf. - Create a dedicated system user (e.g.,
mongodb) and structure your directories for data, logs, and configuration.
Example YAML-based configuration snippet:
systemLog:
destination: file
path: "/var/log/mongodb/mongod.log"
logAppend: true
storage:
dbPath: "/var/lib/mongodb"
journal:
enabled: true
net:
port: 27017
bindIp: 127.0.0.1,192.168.1.10
security:
authorization: enabled
5. Basic Operations
Interacting with MongoDB is typically done via the mongosh shell:
- Create/Switch Database:
use my_app_db - Insert Data:
db.users.insertOne({ name: "Alice", role: "admin" }) - Query Data:
db.users.find({ name: "Alice" }).pretty() - Drop Collection:
db.users.drop()
6. Security and Access Control
Authentication should be enabled in production. Always create a root user in the admin database to manage cluster-wide permissions:
use admin
db.createUser({
user: "adminUser",
pwd: "securePassword123",
roles: [{ role: "root", db: "admin" }]
})
7. Replication Sets
MongoDB uses Replication Sets to ensure high availability. A typical set consists of one Primary node (for writes) and multiple Secondary nodes (for reads). If the Primary fails, the set performs an automated election to promote a new Primary.
To initialize a set in the shell:
rs.initiate({
_id: "my_cluster",
members: [
{ _id: 0, host: "node1:27017" },
{ _id: 1, host: "node2:27017" },
{ _id: 2, host: "node3:27017" }
]
})
8. Sharded Clusters
Sharding enables horizontal scaling by distributing data across multiple machines. It involves three components:
- Shards: Store the actual data subsets.
- Config Servers: Store metadata and cluster configuration.
- mongos: Act as a query router, directing requests to the appropriate shard.
9. Backup and Restoration
For routine maintenance, use the binary utilities mongodump and mongorestore, which operate on BSON files. For cross-platform migrations, use mongoexport and mongoimport to interact with JSON/CSV formats.
Example Backup Command:
mongodump --host localhost --port 27017 --username admin --authenticationDatabase admin --db my_db --out /backups/db_snapshot