3. MongoDB
A comprehensive MongoDB guide covering core concepts, advanced features, and how it handles things like foreign keys, relationships, and beyond β all in one place.
π MongoDB Comprehensive Guide
1. πΉ What is MongoDB?
- MongoDB is a NoSQL database that stores data in JSON-like documents (BSON).
- Itβs schema-less by default β meaning documents in a collection can have different structures.
- Used for scalable, high-performance apps β especially in Node.js/Express ecosystems.
2. πΉ Basic Building Blocks
Concept | MongoDB Equivalent |
---|---|
Database | Database |
Table | Collection |
Row | Document |
Column | Field |
Primary Key | _id field (auto-gen) |
3. πΉ Data Types
MongoDB supports:
String
,Number
,Boolean
Array
,Object
Date
ObjectId
(unique identifier)Null
4. πΉ CRUD Operations
πΈ Create
db.users.insertOne({ name: "Alice", age: 30 })
πΈ Read
db.users.find({ name: "Alice" })
πΈ Update
db.users.updateOne({ name: "Alice" }, { $set: { age: 31 } })
πΈ Delete
db.users.deleteOne({ name: "Alice" })
5. πΉ Schema Design (Mongoose)
You can enforce structure using Mongoose in Node.js:
const userSchema = new mongoose.Schema({ name: String, email: { type: String, unique: true }, age: Number});
6. πΉ Relationships in MongoDB
MongoDB is non-relational, but you can model relationships in two ways:
A. Embedding (Denormalization)
{ name: "Alice", orders: [ { product: "Book", quantity: 2 }, { product: "Pen", quantity: 5 } ]}
β Great for fast reads, fewer joins.
B. Referencing (Normalization)
// users{ _id: ObjectId("u1"), name: "Alice" }
// orders{ userId: ObjectId("u1"), product: "Book" }
You can manually βjoinβ with populate()
in Mongoose:
Order.find().populate('userId');
β¨ How it works:
.populate('userId')
works only if youβve told Mongoose how userId
is related in your schema.
So the key is setting up the reference properly.
β Example: Setting Up the Relationship
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({ name: String, email: String});
module.exports = mongoose.model('User', userSchema);
const mongoose = require('mongoose');
const orderSchema = new mongoose.Schema({ product: String, userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User' // <--- THIS tells Mongoose to link with the User model }});
module.exports = mongoose.model('Order', orderSchema);
Now when you run this:
Order.find().populate('userId')
Mongoose:
- Sees
userId
is a reference (ref: 'User'
) - Looks up the User model
- Replaces
userId
with the actual User document
π§ͺ Output Before .populate()
{ _id: "order1", product: "Book", userId: "662ac3f9d25a10a9f1b821ad"}
β
Output After .populate()
{ _id: "order1", product: "Book", userId: { _id: "662ac3f9d25a10a9f1b821ad", name: "Alice", email: "alice@example.com" }}
β οΈ Common Mistakes
- β Forgetting
ref: 'User'
in the schema - β Using string instead of
mongoose.Schema.Types.ObjectId
- β The referenced document (
User
) doesnβt exist - β Typo in the model name (
ref: 'user'
instead of'User'
)
7. πΉ Does MongoDB Support Foreign Keys?
Not natively like SQL.
MongoDB:
- Doesnβt enforce foreign keys.
- You can manually manage relations and use tools like Mongoose to simulate joins.
In Mongoose:
const orderSchema = new mongoose.Schema({ userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, product: String});
8. πΉ Indexes
Indexes improve query performance.
db.users.createIndex({ email: 1 }, { unique: true });
Mongoose:
email: { type: String, unique: true }
9. πΉ Aggregation Framework
Powerful for data analysis, transformation, and group operations.
db.orders.aggregate([ { $match: { status: "complete" } }, { $group: { _id: "$userId", total: { $sum: "$amount" } } }])
10. πΉ Transactions (ACID Support)
- MongoDB supports multi-document ACID transactions in replica sets (4.0+).
- Use them when you really need SQL-like reliability.
const session = await mongoose.startSession();session.startTransaction();
try { await User.create([{ name: 'Bob' }], { session }); await Order.create([{ product: 'Book' }], { session }); await session.commitTransaction();} catch (err) { await session.abortTransaction();}
11. πΉ Advanced Features
Feature | Description |
---|---|
π Role-based Access | Manage users/roles with db.createUser() |
βοΈ MongoDB Atlas | Cloud-hosted MongoDB with backups, scaling, monitoring |
π¦ Validation | Enforce schemas using Mongoose or MongoDB validator rules |
π Change Streams | Real-time event listeners for DB changes |
π Full-text Search | Native support for $text search and indexes |
12. πΉ MongoDB vs SQL: Quick Comparison
Feature | MongoDB | SQL (MySQL, Postgres) |
---|---|---|
Data Format | BSON (JSON-like) | Tables (rows/columns) |
Schema | Flexible (optional) | Strict (defined) |
Relationships | Manual (populate, ref) | Foreign keys, joins |
Scalability | Easy to scale horizontally (shards) | Can be harder to scale |
Performance | Fast for unstructured data | Great for relational data |
π Recommended Tools
- MongoDB Compass: Visual GUI
- MongoDB Atlas: Cloud DB hosting
- Mongoose: ODM for Node.js
- Robo 3T: Lightweight DB GUI
- Postman: API testing