MongoDB Introduction
Understanding the fundamentals of MongoDB
🍃 What is MongoDB?
MongoDB is a document-oriented NoSQL database that stores data in flexible JSON-like documents. It's designed for scalability, high performance, and developer-friendly data modeling.
// A MongoDB document
{
_id: ObjectId("507f1f77bcf86cd799439011"),
name: "John Doe",
email: "[email protected]",
age: 30
}
Key MongoDB Concepts
MongoDB organizes data differently than traditional SQL databases. Instead of tables and rows, it uses collections and documents, providing flexibility and scalability for modern applications.
Documents
Data stored as JSON-like objects
{ name: "Alice", age: 25 }
Collections
Groups of related documents
db.users.find()
Databases
Container for collections
use myDatabase
_id Field
Unique identifier for documents
_id: ObjectId("...")
🔹 MongoDB vs SQL Terminology
Understanding how MongoDB concepts map to SQL helps transition from relational databases:
| SQL | MongoDB |
|---|---|
| Database | Database |
| Table | Collection |
| Row | Document |
| Column | Field |
| JOIN | Embedded Documents / $lookup |
🔹 Document Structure
MongoDB documents are stored in BSON (Binary JSON) format, supporting various data types:
// A complete MongoDB document
{
_id: ObjectId("507f1f77bcf86cd799439011"),
name: "John Doe",
email: "[email protected]",
age: 30,
active: true,
roles: ["user", "admin"],
address: {
street: "123 Main St",
city: "New York",
zip: "10001"
},
createdAt: new Date("2024-01-15")
}
Supported Data Types:
- String, Number, Boolean
- Array, Object (Embedded Document)
- Date, ObjectId, Null
- Binary Data, Regular Expression
🔹 Collections in MongoDB
Collections are groups of documents, similar to tables in SQL but without a fixed schema:
// Create a collection (implicit)
db.users.insertOne({ name: "Alice" })
// Create a collection (explicit)
db.createCollection("products")
// List all collections
show collections
// Drop a collection
db.users.drop()
Output:
{ acknowledged: true, insertedId: ObjectId("...") }
{ ok: 1 }
products
users
true
🔹 Flexible Schema
Unlike SQL, MongoDB doesn't require a predefined schema. Documents in the same collection can have different fields:
// First document
db.users.insertOne({
name: "Alice",
email: "[email protected]"
})
// Second document with different fields
db.users.insertOne({
name: "Bob",
email: "[email protected]",
phone: "555-1234",
address: {
city: "Boston"
}
})
// Both documents exist in the same collection
db.users.find()
Output:
{ _id: ObjectId("..."), name: "Alice", email: "[email protected]" }
{ _id: ObjectId("..."), name: "Bob", email: "[email protected]", phone: "555-1234", address: { city: "Boston" } }
🔹 Embedded Documents vs References
MongoDB offers two ways to model relationships between data:
🔸 Embedded Documents (Denormalized)
// User with embedded address
{
_id: 1,
name: "Alice",
address: {
street: "123 Main St",
city: "New York"
}
}
🔸 References (Normalized)
// User document
{
_id: 1,
name: "Alice",
addressId: 100
}
// Address document
{
_id: 100,
street: "123 Main St",
city: "New York"
}
🔹 MongoDB Features
Key features that make MongoDB powerful for modern applications:
🔍 Rich Queries
Powerful query language with filtering, sorting, and aggregation
📊 Indexing
Fast data retrieval with various index types
🔄 Replication
High availability with replica sets
⚖️ Sharding
Horizontal scaling across multiple servers
🔐 Security
Authentication, authorization, and encryption
📈 Aggregation
Complex data processing pipelines
🔹 When to Use MongoDB
MongoDB is ideal for specific use cases:
✅ Good Use Cases:
- Rapidly changing data structures
- Large volumes of unstructured data
- Real-time analytics and logging
- Content management systems
- Mobile and IoT applications
- Catalogs and product information
❌ Not Ideal For:
- Complex multi-row transactions
- Heavy relational data with many joins
- Legacy systems requiring SQL