✦ Quick summary
MongoDB is a document database that stores data as flexible JSON/BSON, ideal when schema changes frequently. Learn CRUD, Aggregation Pipeline, Replica Sets, and when to choose MongoDB over PostgreSQL.
How was this post?

MongoDB is the world's leading document database, storing data as flexible JSON instead of fixed tables like SQL. This article explains what MongoDB is, how the document model works, the Aggregation Pipeline, and when to choose MongoDB over PostgreSQL.

What is MongoDB?

MongoDB is a document NoSQL database management system, created in 2009. Instead of storing data in tables with fixed rows and columns like SQL, MongoDB stores data as flexible JSON documents (technically BSON — Binary JSON):

JSON
 1{
 2  "_id": "64a1f2...",
 3  "name": "Alice",
 4  "email": "alice@example.com",
 5  "orders": [
 6    { "product": "Laptop", "price": 999 },
 7    { "product": "Mouse", "price": 29 }
 8  ],
 9  "address": {
10    "city": "Hanoi",
11    "district": "Hoan Kiem"
12  }
13}

A single user document contains embedded orders — something that is unnatural in SQL and requires JOINs across multiple tables.

Document Model vs Relational Model

MongoDB (Document) PostgreSQL (Relational)
Storage unit Document (JSON) Row in a table
Schema Flexible (not fixed) Fixed (requires migration)
Data relationships Embed or reference Foreign key + JOIN
Scaling Horizontal (sharding) Vertical (primarily)
Transactions Multi-document (4.0+) Full ACID

CRUD with pymongo (Python)

Python
 1from pymongo import MongoClient
 2
 3client = MongoClient("mongodb://localhost:27017/")
 4db = client["myapp"]
 5users = db["users"]
 6
 7# Insert
 8result = users.insert_one({
 9    "name": "Alice",
10    "email": "alice@example.com",
11    "active": True
12})
13print(result.inserted_id)  # ObjectId('64a1f2...')
14
15# Find with filter
16active_users = users.find({"active": True}, {"name": 1, "email": 1})
17for user in active_users:
18    print(user)
19
20# Update
21users.update_one(
22    {"email": "alice@example.com"},
23    {"$set": {"active": False}}
24)
25
26# Delete
27users.delete_one({"email": "alice@example.com"})

Node.js with Mongoose

JavaScript
 1const mongoose = require('mongoose');
 2await mongoose.connect('mongodb://localhost:27017/myapp');
 3
 4const UserSchema = new mongoose.Schema({
 5  name: { type: String, required: true },
 6  email: { type: String, required: true, unique: true },
 7  active: { type: Boolean, default: true },
 8});
 9
10const User = mongoose.model('User', UserSchema);
11
12// Create
13const user = await User.create({ name: 'Alice', email: 'alice@example.com' });
14
15// Find
16const activeUsers = await User.find({ active: true }).select('name email');
17
18// Update
19await User.updateOne({ email: 'alice@example.com' }, { $set: { active: false } });

Aggregation Pipeline

JavaScript
 1// Revenue by month
 2db.orders.aggregate([
 3  { $match: { status: "completed" } },
 4  { $group: {
 5      _id: { $month: "$createdAt" },
 6      totalRevenue: { $sum: "$amount" },
 7      orderCount: { $sum: 1 }
 8  }},
 9  { $sort: { "_id": 1 } }
10])

Replica Sets and High Availability

A MongoDB Replica Set consists of one Primary and one or more Secondaries. The Primary accepts all writes; Secondaries continuously replicate from the Primary. If the Primary fails, the Replica Set automatically elects a new Primary within seconds — providing zero downtime for the application.

When to Choose MongoDB vs PostgreSQL?

Choose MongoDB when the schema is unstable, data is naturally nested, or you need fast horizontal scaling. Choose PostgreSQL when you need complex JOINs, full ACID compliance, or heavy reporting and analytics.

What is PostgreSQL? The leading relational database management system

What is Elasticsearch? Distributed search engine for full-text search

What is Redis? In-memory cache, Pub/Sub, and queues

Frequently Asked QuestionsQ&A
What format does MongoDB use to store data?
MongoDB stores data as BSON (Binary JSON) — a binary-encoded extension of JSON that adds types like Date, ObjectId, Binary, and Decimal128. When working through a driver you see regular JSON; MongoDB automatically converts to BSON for storage.
Does MongoDB support transactions?
Yes, since MongoDB 4.0 (2018). MongoDB supports multi-document ACID transactions on replica sets, and since 4.2 on sharded clusters. However, transactions in MongoDB carry higher overhead than PostgreSQL, so use them only when you truly need multiple documents updated atomically.
What is a Replica Set in MongoDB?
A Replica Set is a group of MongoDB instances that maintain the same dataset: one Primary accepts all writes, while one or more Secondaries continuously replicate data from the Primary. If the Primary fails, the Replica Set automatically elects a new Primary within seconds — this is MongoDB's basic high-availability mechanism.
What is the Aggregation Pipeline?
The Aggregation Pipeline is a sequence of data-processing stages run in order: $match (filter documents), $group (aggregate computations like COUNT, SUM, AVG), $sort, $project (select fields), $lookup (JOIN with another collection). Each stage receives the output of the previous stage, enabling complex analytical queries.
When should I choose MongoDB over PostgreSQL?
Choose MongoDB when: the schema changes frequently or is not yet well-defined (agile development), data has naturally nested structures (product catalogs with different attributes per category), you need fast horizontal scaling with sharding, or your team is more comfortable with JavaScript/JSON than SQL. Choose PostgreSQL when you need complex JOINs, strict ACID guarantees, or data with tight relational constraints.
What is MongoDB Atlas?
MongoDB Atlas is a fully managed MongoDB service on the cloud (AWS, GCP, Azure). Atlas automatically handles backups, scaling, security patches, and monitoring. There is a free tier (M0: 512 MB) suitable for learning and prototyping. Production workloads typically use M10 or higher with a dedicated cluster.