MongoDB is the most popular NoSQL database. Instead of tables and rows, it stores data as flexible JSON-like documents in collections. This lesson covers MongoDB's document model, CRUD operations, and schema design patterns.
Documents and Collections
In MongoDB, data is organized into databases, collections, and documents:
Database: myapp
Collection: users
Document: { _id: "...", name: "Alice", email: "a@mail.co" }
Document: { _id: "...", name: "Bob", email: "b@mail.co" }
Collection: posts
Document: { _id: "...", title: "Hello World", author: "Alice" }A document is a JSON object (technically BSON — Binary JSON). Unlike SQL rows, documents in the same collection can have different fields.
Setting Up
Install the MongoDB Node.js driver or Mongoose (an ODM — Object Document Mapper):
npm install mongooseConnect to MongoDB:
Defining Schemas with Mongoose
Although MongoDB is schemaless, Mongoose lets you define schemas for validation and structure:
CRUD Operations
Create
Read
Query Operators
Operator Reference
| Operator | Meaning | Example |
|---|---|---|
$eq | Equal | { age: { $eq: 25 } } |
$gt | Greater than | { price: { $gt: 100 } } |
$gte | Greater than or equal | { score: { $gte: 70 } } |
$lt | Less than | { stock: { $lt: 5 } } |
$in | In array | { role: { $in: ["admin"] } } |
$or | Logical OR | { $or: [cond1, cond2] } |
$and | Logical AND | { $and: [cond1, cond2] } |
$regex | Pattern match | { name: { $regex: /^A/i } } |
Update
Delete
await User.findByIdAndDelete(userId);
await User.deleteOne({ email: "old@example.com" });
await User.deleteMany({ isActive: false });Embedding vs Referencing
The biggest design decision in MongoDB is whether to embed related data or reference it.
Embedding (Denormalized)
Store related data inside the parent document:
Use embedding when:
- The related data is always accessed together
- The embedded array will not grow unboundedly
- The data does not need to be queried independently
Referencing (Normalized)
Store a reference (ID) to a document in another collection:
Use referencing when:
- The related data is large or accessed independently
- The related data changes frequently
- You need to query the related data on its own
Aggregation Pipeline
MongoDB's aggregation pipeline lets you process data in stages:
Practical Exercise
Build a blog schema with MongoDB:
Key Takeaways
- MongoDB stores data as flexible JSON-like documents grouped into collections.
- Mongoose adds schema validation and convenience methods on top of the native driver.
- Choose embedding for tightly coupled data and referencing for independent, large, or frequently changing data.
- Query operators like
$gt,$in,$or, and$regexgive you powerful filtering capabilities. - The aggregation pipeline processes data in stages for complex analytics queries.