Databases Lesson 8: MongoDB (NoSQL)
MongoDB stores data as JSON-like documents. No schema, no joins required — great for flexible data structures and rapid development.
Core Concepts
// SQL → MongoDB mapping:
// Database → Database
// Table → Collection
// Row → Document
// Column → Field
// JOIN → $lookup (or embed documents)
// A MongoDB document:
{
_id: ObjectId("..."),
name: "Alice",
email: "alice@example.com",
address: { // embedded document
city: "NYC",
country: "USA"
},
tags: ["admin", "beta"], // arrays natively!
orders: [ // embedded array
{ product: "Laptop", price: 999, date: ISODate("2024-01-15") }
]
}
CRUD Operations
// Insert
db.users.insertOne({ name: "Alice", age: 30 });
db.users.insertMany([{ name: "Bob" }, { name: "Charlie" }]);
// Find
db.users.find(); // all
db.users.find({ age: { $gt: 25 } }); // where age > 25
db.users.findOne({ email: "a@b.com" }); // one document
// Update
db.users.updateOne({ email: "a@b.com" }, { $set: { age: 31 } });
db.users.updateMany({ role: "user" }, { $set: { active: true } });
// Delete
db.users.deleteOne({ _id: id });
db.users.deleteMany({ active: false });
Aggregation Pipeline
db.orders.aggregate([
{ $match: { status: "completed" } }, // filter
{ $group: { _id: "$userId", total: { $sum: "$amount" } } }, // group
{ $sort: { total: -1 } }, // sort
{ $limit: 10 }, // top 10
{ $lookup: { // join users collection
from: "users", localField: "_id",
foreignField: "_id", as: "user"
} }
]);
🏋️ Practice Task
Build a blog with MongoDB (use Mongoose or direct MongoDB driver). Schema: posts with embedded comments array, authors as reference. Implement: create post, add comment (push to array), find posts by tag, aggregate top authors by post count.
💡 Hint: db.posts.updateOne({_id: postId}, {$push: {comments: {text, author, date: new Date()}}})