Getting Started
MongoDB Introduction
Learn MongoDB — the popular NoSQL database that stores data as flexible JSON documents.
What is MongoDB?
MongoDB is a document-oriented NoSQL database. Instead of storing data in rows and columns (like SQL), it stores data as documents — flexible, JSON-like structures.
SQL vs MongoDB Terminology
| SQL | MongoDB |
|---|---|
| Database | Database |
| Table | Collection |
| Row | Document |
| Column | Field |
| JOIN | $lookup (aggregation) |
| Primary Key | _id |
When to Use MongoDB
Good for:
- Applications with evolving schemas
- Hierarchical/nested data
- High-volume, low-latency operations
- Horizontal scaling needs
Not ideal for:
- Complex transactions across many collections
- Strong relational data with many JOINs
- When data consistency is paramount
BSON
MongoDB stores data as BSON (Binary JSON), which extends JSON with additional types like ObjectId, Date, and BinData.
Example
javascript
// Documents look like JavaScript objects
{
"_id": ObjectId("507f1f77bcf86cd799439011"),
"name": "Alice Johnson",
"email": "alice@example.com",
"age": 30,
"address": {
"city": "Paris",
"country": "France"
},
"hobbies": ["reading", "coding", "hiking"],
"createdAt": ISODate("2024-01-15T10:30:00Z")
}
// MongoDB shell commands
// show dbs -- list databases
// use myapp -- switch to database
// show collections -- list collections
// db.users.find() -- query collection
// MongoDB Atlas (cloud) connection string
// mongodb+srv://username:password@cluster.mongodb.net/myapp
// Mongoose (Node.js ODM)
// npm install mongooseWant to run this code interactively?
Try in Compiler