MongoDB is a document-oriented NoSQL database designed for high scalability, flexibility, and performance. It is widely used in modern web applications, microservices, real-time systems, analytics platforms, and large-scale distributed architectures.
1. What Is MongoDB?
MongoDB is a schema-less document database that stores data in BSON (Binary JSON) format.
Key Characteristics
- No fixed schema
- Stores data as documents (JSON-like)
- Horizontal scalability (sharding)
- High availability (replica sets)
- Rich query language
- Built-in aggregation framework
2. MongoDB Data Model
Hierarchy
MongoDB Server
└── Database
└── Collection
└── Document
└── Fields
Example Document
{
"_id": ObjectId("65a1f0c7e4b0a12f90e1c111"),
"name": "Farhad",
"age": 25,
"skills": ["JavaScript", "MongoDB"],
"isActive": true
}
3. BSON Internals (How Data Is Stored)
MongoDB does not store JSON directly. It uses BSON.
BSON Advantages
- Binary encoded
- Faster parsing
- Supports additional types
BSON Data Types
| Type | Example |
|---|---|
| String | "text" |
| Int32 | NumberInt(10) |
| Int64 | NumberLong(100) |
| Double | 10.5 |
| Boolean | true |
| Date | ISODate() |
| ObjectId | ObjectId() |
| Array | [] |
| Embedded Document | {} |
| Null | null |
4. MongoDB Architecture (High-Level)
Core Components
- mongod → database engine
- mongos → query router (sharding)
- Replica Set
- Shards
- Config Servers
5. mongod Internals
mongod is the main MongoDB server process.
Responsibilities
- Query execution
- Index management
- Replication
- Storage engine interaction
6. Storage Engine (WiredTiger)
MongoDB uses WiredTiger by default.
WiredTiger Features
- Document-level locking
- MVCC (Multi-Version Concurrency Control)
- Compression
- Journaling
Memory Model
- Cache (RAM)
- Disk persistence
- Checkpoints
7. MongoDB Journaling (Durability)
MongoDB ensures durability using write-ahead logging.
Write → Journal → Memory → Disk
Enable Journaling
mongod --journal
8. Replica Sets (High Availability)
A replica set is a group of MongoDB servers maintaining the same data.
Roles
- Primary
- Secondary
- Arbiter
Replica Set Diagram
Primary
├── Secondary
├── Secondary
└── Arbiter
Initialize Replica Set
rs.initiate()
9. Sharding (Horizontal Scaling)
Sharding splits data across multiple machines.
Components
- Shards
- mongos
- Config Servers
Enable Sharding
sh.enableSharding("mydb")
Shard a Collection
sh.shardCollection("mydb.users", { userId: 1 })
10. Databases & Collections
Create Database
use myDatabase
Create Collection
db.createCollection("users")
Capped Collection
db.createCollection("logs", { capped: true, size: 1024 })
11. CRUD Operations (Full Syntax)
Insert Documents
insertOne
db.users.insertOne({
name: "Ali",
age: 30
})
insertMany
db.users.insertMany([
{ name: "A", age: 20 },
{ name: "B", age: 25 }
])
Read Documents
find
db.users.find()
findOne
db.users.findOne({ name: "Ali" })
Projection
db.users.find({}, { name: 1, _id: 0 })
Query Operators
Comparison
db.users.find({ age: { $gt: 18 } })
| Operator | Meaning |
|---|---|
$eq |
equals |
$ne |
not equal |
$gt |
greater |
$gte |
greater or equal |
$lt |
less |
$lte |
less or equal |
Logical
db.users.find({
$and: [{ age: { $gt: 18 } }, { isActive: true }]
})
| Operator | Meaning |
|---|---|
$and |
AND |
$or |
OR |
$not |
NOT |
$nor |
NOR |
Update Documents
updateOne
db.users.updateOne(
{ name: "Ali" },
{ $set: { age: 31 } }
)
updateMany
db.users.updateMany(
{ isActive: false },
{ $set: { archived: true } }
)
Operators
| Operator | Function |
|---|---|
$set |
set value |
$unset |
remove field |
$inc |
increment |
$push |
add to array |
$pull |
remove from array |
Delete Documents
deleteOne
db.users.deleteOne({ name: "Ali" })
deleteMany
db.users.deleteMany({ age: { $lt: 18 } })
12. Indexing (Performance)
Create Index
db.users.createIndex({ email: 1 })
Compound Index
db.users.createIndex({ age: 1, name: 1 })
Unique Index
db.users.createIndex({ email: 1 }, { unique: true })
Text Index
db.posts.createIndex({ content: "text" })
13. Aggregation Framework (Core Feature)
Pipeline Stages
| Stage | Description |
|---|---|
$match |
filter |
$group |
grouping |
$project |
reshape |
$sort |
sort |
$limit |
limit |
$skip |
skip |
$lookup |
join |
$unwind |
flatten array |
Example
db.orders.aggregate([
{ $match: { status: "paid" } },
{
$group: {
_id: "$userId",
total: { $sum: "$amount" }
}
}
])
14. Relationships in MongoDB
Embedded
{
"name": "User",
"address": { "city": "Kabul" }
}
Referenced
{
"userId": ObjectId("...")
}
15. Transactions (ACID)
MongoDB supports multi-document transactions.
const session = db.getMongo().startSession()
session.startTransaction()
try {
session.getDatabase("shop").orders.insertOne({ total: 100 })
session.commitTransaction()
} catch (e) {
session.abortTransaction()
}
16. Security
Authentication
- SCRAM
- X.509
- LDAP
Authorization (RBAC)
db.createUser({
user: "admin",
pwd: "password",
roles: ["readWrite"]
})
17. Backup & Restore
Backup
mongodump --db mydb
Restore
mongorestore mydb
18. MongoDB Compass & Shell
Shell Commands
mongosh
Compass
- GUI for querying
- Schema visualization
- Index management
19. MongoDB Use Cases
- Web applications
- Real-time analytics
- IoT
- CMS
- Social networks
- Microservices
20. MongoDB vs SQL (Quick Comparison)
| Feature | MongoDB | SQL |
|---|---|---|
| Schema | Flexible | Fixed |
| Joins | Limited | Strong |
| Scaling | Horizontal | Vertical |
| Transactions | Yes | Yes |
21. Best Practices
- Use indexes wisely
- Avoid unbounded arrays
- Prefer embedding for performance
- Monitor memory usage
- Design shard keys carefully
22. Conclusion
MongoDB is a powerful, flexible, and scalable database built for modern applications. Understanding its internals, architecture, and full query syntax allows developers to build high-performance, fault-tolerant systems at scale.
If you master MongoDB deeply, you can confidently design real-world production databases without limitations.
Top comments (0)