What is MongoDB? Document Database and When to Choose NoSQL
Database

What is MongoDB? Document Database and When to Choose NoSQL

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.

✦ 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.

MongoDB là document database hàng đầu thế giới, lưu dữ liệu dạng JSON linh hoạt thay vì bảng cố định như SQL. Bài viết giải thích MongoDB là gì, cách hoạt động của document model, Aggregation Pipeline, và khi nào nên chọn MongoDB thay vì PostgreSQL.

MongoDB là gì?

MongoDB là hệ quản trị cơ sở dữ liệu NoSQL dạng document, ra đời năm 2009. Thay vì lưu dữ liệu trong bảng với rows và columns cố định như SQL, MongoDB lưu dữ liệu dạng document JSON (thực tế là BSON — Binary JSON) linh hoạt:

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": "Hà Nội",
11    "district": "Hoàn Kiếm"
12  }
13}

Một user document chứa cả orders lồng bên trong — điều không tự nhiên trong SQL đòi hỏi JOIN qua nhiều bảng.

Document Model vs Relational Model

MongoDB (Document) PostgreSQL (Relational)
Đơn vị lưu trữ Document (JSON) Row trong bảng
Schema Flexible (không cố định) Fixed (cần migration)
Quan hệ dữ liệu Embed hoặc reference Foreign key + JOIN
Scale Horizontal (sharding) Vertical (chủ yếu)
Transaction Multi-document (4.0+) Đầy đủ ACID

CRUD với pymongo (Python)

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

Node.js với Mongoose

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

Aggregation Pipeline

JavaScript
 1// Doanh thu theo tháng
 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])

Elasticsearch là gì? Search engine phân tán cho full-text search

Replica Set và High Availability

MongoDB Replica Set gồm một Primary và một hoặc nhiều Secondary. Primary nhận mọi write; Secondary liên tục replication từ Primary. Nếu Primary fail, Replica Set tự bầu Primary mới trong vài giây — zero downtime cho ứng dụng.

Redis là gì? Cache, Pub/Sub và hàng đợi in-memory

Khi nào chọn MongoDB vs PostgreSQL?

Chọn MongoDB khi schema chưa ổn định, dữ liệu lồng nhau tự nhiên, hoặc cần scale horizontal nhanh. Chọn PostgreSQL khi cần JOIN phức tạp, ACID đầy đủ, hoặc reporting/analytics nặng.

PostgreSQL là gì? Hệ quản trị cơ sở dữ liệu quan hệ hàng đầu

Câu hỏi thường gặpQ&A
MongoDB lưu dữ liệu dưới định dạng nào?
MongoDB lưu dữ liệu dạng BSON (Binary JSON) — một định dạng binary mở rộng của JSON, hỗ trợ thêm các kiểu như Date, ObjectId, Binary, và Decimal128. Khi làm việc qua driver, bạn thấy JSON thông thường; MongoDB tự chuyển đổi sang BSON khi lưu trữ.
MongoDB có hỗ trợ transaction không?
Có, từ MongoDB 4.0 (2018). MongoDB hỗ trợ multi-document ACID transaction trên replica set, và từ 4.2 hỗ trợ trên sharded cluster. Tuy nhiên transaction trong MongoDB có overhead cao hơn PostgreSQL, nên chỉ dùng khi thực sự cần nhiều document cập nhật đồng thời.
Replica Set trong MongoDB là gì?
Replica Set là nhóm MongoDB instances lưu cùng một bộ dữ liệu: một Primary nhận mọi write, một hoặc nhiều Secondary liên tục sao chép dữ liệu từ Primary (replication). Nếu Primary fail, Replica Set tự bầu chọn Secondary mới làm Primary trong vài giây — đây là cơ chế high availability cơ bản của MongoDB.
Aggregation Pipeline là gì?
Aggregation Pipeline là chuỗi các stage xử lý dữ liệu tuần tự: $match (filter documents), $group (tính toán tổng hợp như COUNT, SUM, AVG), $sort, $project (chọn field), $lookup (JOIN với collection khác). Mỗi stage nhận output của stage trước, cho phép xây dựng query phân tích phức tạp.
Khi nào nên chọn MongoDB thay vì PostgreSQL?
Chọn MongoDB khi: schema thay đổi thường xuyên hoặc chưa xác định rõ (agile development), dữ liệu có cấu trúc lồng nhau tự nhiên (product catalog với attributes khác nhau per category), cần scale horizontal nhanh với sharding, hoặc team quen với JavaScript/JSON hơn SQL. Chọn PostgreSQL khi cần JOIN phức tạp, ACID nghiêm ngặt, hoặc dữ liệu có quan hệ chặt chẽ.
MongoDB Atlas là gì?
MongoDB Atlas là dịch vụ MongoDB quản lý hoàn toàn (managed) trên cloud (AWS, GCP, Azure). Atlas tự động xử lý backup, scaling, security patch và monitoring. Có free tier (M0: 512MB) phù hợp học tập và prototype. Production thường dùng M10 trở lên với dedicated cluster.