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.
Need data solutions for your business?
AlgoData has helped businesses with data engineering, analytics & AI since 2019.
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):

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)
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
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

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

