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
Section titled โ๐ MongoDB Comprehensive Guideโ1. ๐น What is MongoDB?
Section titled โ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
Section titled โ2. ๐น Basic Building Blocksโ| Concept | MongoDB Equivalent |
|---|---|
| Database | Database |
| Table | Collection |
| Row | Document |
| Column | Field |
| Primary Key | _id field (auto-gen) |
3. ๐น Data Types
Section titled โ3. ๐น Data TypesโMongoDB supports:
String,Number,BooleanArray,ObjectDateObjectId(unique identifier)Null
4. ๐น CRUD Operations
Section titled โ4. ๐น CRUD Operationsโ๐ธ Create
Section titled โ๐ธ Createโdb.users.insertOne({ name: "Alice", age: 30 })๐ธ Read
Section titled โ๐ธ Readโdb.users.find({ name: "Alice" })๐ธ Update
Section titled โ๐ธ Updateโdb.users.updateOne({ name: "Alice" }, { $set: { age: 31 } })๐ธ Delete
Section titled โ๐ธ Deleteโdb.users.deleteOne({ name: "Alice" })5. ๐น Schema Design (Mongoose)
Section titled โ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
Section titled โ6. ๐น Relationships in MongoDBโMongoDB is non-relational, but you can model relationships in two ways:
A. Embedding (Denormalization)
Section titled โA. Embedding (Denormalization)โ{ name: "Alice", orders: [ { product: "Book", quantity: 2 }, { product: "Pen", quantity: 5 } ]}โ Great for fast reads, fewer joins.
B. Referencing (Normalization)
Section titled โ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:
Section titled โโจ 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
Section titled โโ 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
userIdis a reference (ref: 'User') - Looks up the User model
- Replaces
userIdwith the actual User document
๐งช Output Before .populate()
Section titled โ๐งช Output Before .populate()โ{ _id: "order1", product: "Book", userId: "662ac3f9d25a10a9f1b821ad"}โ
Output After .populate()
Section titled โโ
Output After .populate()โ{ _id: "order1", product: "Book", userId: { _id: "662ac3f9d25a10a9f1b821ad", name: "Alice", email: "alice@example.com" }}โ ๏ธ Common Mistakes
Section titled โโ ๏ธ 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?
Section titled โ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
Section titled โ8. ๐น IndexesโIndexes improve query performance.
db.users.createIndex({ email: 1 }, { unique: true });Mongoose:
email: { type: String, unique: true }9. ๐น Aggregation Framework
Section titled โ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)
Section titled โ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
Section titled โ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
Section titled โ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
Section titled โ๐ Recommended Toolsโ- MongoDB Compass: Visual GUI
- MongoDB Atlas: Cloud DB hosting
- Mongoose: ODM for Node.js
- Robo 3T: Lightweight DB GUI
- Postman: API testing