Document-Oriented Architecture vs Relational Tables
Learn how MongoDB stores unstructured and polymorphic data in flexible BSON documents and master core CRUD commands.
The NoSQL Document Paradigm
Unlike relational databases with rigid schemas, MongoDB stores records as flexible BSON (Binary JSON) documents inside collections. Fields can vary from document to document, making MongoDB ideal for agile, rapidly evolving web systems.
// MongoDB Insert & Query Syntax
db.courses.insertOne({
title: "MongoDB Architecture",
category: "Databases",
enrolled_learners: 1420,
tags: ["nosql", "database", "mongodb"],
instructor: {
name: "HK1 Tech Editorial",
verified: true
},
published_at: new Date()
});
// Query with filters
db.courses.find({
category: "Databases",
enrolled_learners: { $gte: 1000 }
}).sort({ enrolled_learners: -1 });
Console Output
Press "Run Code" to execute in virtual runtime.
Aggregation Pipelines: $match, $group & $project
Process multi-stage data transformations, statistical grouping, and analytical queries using the native aggregation pipeline.
The Power of Aggregation Pipelines
Aggregation pipelines transform documents through sequential stages: filtering matching items, grouping by categorical keys, computing sums or averages, and sorting outcomes:
db.orders.aggregate([
// Stage 1: Filter completed transactions
{ $match: { status: "completed" } },
// Stage 2: Group by category and compute totals
{
$group: {
_id: "$category",
total_revenue: { $sum: "$amount" },
order_count: { $sum: 1 },
avg_order_value: { $avg: "$amount" }
}
},
// Stage 3: Sort by highest revenue
{ $sort: { total_revenue: -1 } }
]);
Console Output
Press "Run Code" to execute in virtual runtime.
MongoDB NoSQL Knowledge Quiz
Test your understanding of embedding vs referencing and aggregation pipeline stages.
MongoDB Production Projects
Build a Social Network Activity Feed and an E-Commerce Inventory Ledger.
Design a document schema optimized for high read throughput supporting posts, nested reply comments, like counters, and tags.
db.posts.createIndex({ "author_id": 1, "created_at": -1 });
Implement ACID transactions in MongoDB across inventory and customer order collections using session.startTransaction().
const session = client.startSession();
session.startTransaction();
try {
// updates across multiple collections
await session.commitTransaction();
} catch (e) {
await session.abortTransaction();
}