MongoDB: Introduction to MongoDB
MongoDB is the world's most popular document database—it makes flexible data modeling and high-throughput writes simple and efficient.
This tutorial is designed for backend developers with a basic understanding of JavaScript and Node.js. It starts with the fundamentals of NoSQL and guides you through building production-ready applications using MongoDB and Mongoose.
1. What You'll Learn
- The Background of NoSQL Databases and the Four Major Families
- The History, Design Philosophy, and Version Evolution of MongoDB
- The Core Differences Between the Document Model and the Relational Model
- Differences Between the BSON Data Format and JSON
- MongoDB Atlas Cloud Service vs. On-Premises Deployment
- Use Cases for MongoDB in Three Major Target Markets (Middle East, Brazil, and Japan)
2. A True Story of a Backend Engineer
(1) Pain Point: Relational Databases Can’t Keep Up
Alice is a backend engineer at a cross-border e-commerce company. She recently received an urgent request:
"Our
productstable already has 2 million records. The operations team has to upload 50,000 new SKUs every day, and each SKU has 10–15 dynamic attributes (such as color, size, battery capacity, and screen refresh rate). Changing the table structure requires locking the database for two hours, and the business team is already hitting the table in frustration."
The problems she faces:
| Issue | Impact |
|---|---|
| Rigid table structure | Every time a new attribute is added, an ALTER TABLE statement is required, which affects production services |
| NULL Field Explosion | 90% of fields are NULL, wasting storage space |
| Poor JOIN Performance | Multi-table join queries take 5 seconds or more to respond when processing hundreds of millions of records |
| Low write throughput | High overhead for relational transactions; insert operations become sluggish under high concurrency |
(2) The MongoDB Solution
Rewrite the SKU system using a document model, where each product is a separate JSON-like document.
// MongoDB Document Structure — One document represents an entire product record.
{
_id: ObjectId("..."),
sku: "PHONE-X-256-BLK",
title: "Smartphone X 256GB Black",
price: 599.99,
category: "Electronics",
attributes: { // Nested Documents,No need to JOIN
color: "Black",
storage: "256GB",
screen: "6.5 inch OLED",
battery: "4500mAh",
refresh_rate: "120Hz"
},
tags: ["5g", "amoled", "fast-charging"], // Array Fields
stock: { warehouse_1: 50, warehouse_2: 30 },
created_at: ISODate("2026-07-01T10:00:00Z")
}
(3) Revenue
| Dimension | Relational (MySQL) | MongoDB |
|---|---|---|
| Add a field | ALTER TABLE (table lock) | Insert a new document directly |
| Storing Empty Fields | Takes up space | Does not take up space |
| Heterogeneous Data | Requires a JSON column or EAV table | Native support |
| Horizontal Scaling | Complex (database and table sharding) | Built-in sharding |
| Write Throughput | 5,000 ops/s | 50,000+ ops/s |
3. The Emergence of NoSQL Databases
Concept Overview: NoSQL (Not Only SQL) databases emerged in the late 2000s, driven by the explosion of internet data. Traditional relational databases revealed three major bottlenecks when faced with petabyte-scale data, millions of concurrent connections, and heterogeneous data: fixed schemas unable to adapt to data diversity, difficulties in horizontal scaling, and extremely poor JOIN performance with large data volumes. The core design philosophy of NoSQL is: trading constraints for performance—sacrificing strong consistency and complex joins in exchange for horizontal scalability and high throughput.
How It Works: The four major NoSQL database families each have different data models and consistency guarantees. Key-value stores are the simplest (O(1) read and write operations), document databases are the most versatile (JSON-like model), column-oriented databases excel in write-intensive scenarios, and graph databases excel at relational queries. As a representative of document databases, MongoDB strikes the best balance between flexibility and query capabilities.
(1) Why is NoSQL needed?
In the late 2000s, the volume of data from Internet applications exploded:
- Google needs to store all the web pages on the Internet (BigTable, 2006)
- Amazon Needs to Handle Peak Shopping Demand (Dynamo, 2007)
- Traditional relational databases are struggling to handle petabyte-scale data
(2) The Four Major Families of NoSQL
Key Points Analysis:
- Key-value stores are the simplest—they consist only of keys and values and do not support complex queries, but they offer the highest performance.
- The document database is the most versatile—it supports nesting, arrays, and secondary indexes, making it suitable for most web applications.
- Column-oriented databases excel at data ingestion—data is stored by column family, making them suitable for time series and log data
- Graph databases excel at representing relationships—they natively store nodes and edges, making them well-suited for social networking and recommendation systems.
| Type | Representative | Data Model | Typical Scenarios | Consistency |
|---|---|---|---|---|
| Key-Value | Redis | key → value | Caching, sessions, counters | Eventual consistency |
| Documents | MongoDB | JSON/BSON documents | CMS, e-commerce, IoT logs | Configurable |
| Column Family | Cassandra | Column Family BigTable | Time-series data, write-intensive | Eventual consistency |
| Figure | Neo4j | Nodes + Edges | Social networks, recommendation systems | Strong consistency |
graph LR
A[NoSQL Database] --> B[Key-Value Store<br/>Redis/DynamoDB]
A --> C[Document Database<br/>MongoDB/CouchDB]
A --> D[Columnar Database<br/>Cassandra/HBase]
A --> E[Graph Database<br/>Neo4j/ArangoDB]
style A fill:#cce5ff
style C fill:#d4edda
| Type | Example | Data Model | Typical Scenarios |
|---|---|---|---|
| Key-Value | Redis | key → value | Caching, sessions, counters |
| Documents | MongoDB | JSON/BSON documents | CMS, e-commerce, IoT logs |
| Column Family | Cassandra | Column Family BigTable | Time-series data, write-intensive |
| Figure | Neo4j | Nodes + Edges | Social Networks, Recommendation Systems |
(3) Why is MongoDB the most popular?
Concept Overview: MongoDB has the highest market share among the four major NoSQL database families (ranked No. 1 in the DB-Engines NoSQL rankings) because it strikes the best balance between flexibility and functionality. Compared to key-value stores, MongoDB supports secondary indexes and aggregation pipelines; compared to column-oriented databases, MongoDB supports nested documents and flexible schemas; and compared to graph databases, MongoDB has a lower learning curve.
| Key Advantages of MongoDB | Description | Comparison with Other NoSQL Databases |
|---|---|---|
| JSON-like data model | No learning curve for front-end developers | Redis requires learning the key command |
| Document Nesting | A single record is an entire object tree | Cassandra requires multi-table joins |
| Secondary Indexes | Flexible while maintaining query performance | Redis has no indexes |
| Aggregation Pipeline | More powerful data processing than SQL | Cassandra has limited query capabilities |
| Official Node.js Driver + mongoose | Most comprehensive JS ecosystem | Best among all NoSQL databases |
| Atlas Cloud Services | Create global clusters with a single click | High costs for self-hosting and operations |
4. MongoDB History and Version Evolution
Concept Overview: MongoDB was created by 10gen (now MongoDB Inc.) in 2007 and released as open source in 2009. From its initial use as a simple document store, to version 4.0’s support for multi-document transactions, and on to version 7.0’s support for vector search, MongoDB has evolved from a “NoSQL database incapable of handling complex transactions” into a general-purpose database that “offers both flexible modeling and ACID compliance.”
Evolutionary Timeline: MongoDB’s development can be divided into three phases—the foundational capabilities phase (1.x–3.x: core CRUD + replica sets + sharding), the enterprise capabilities phase (4.x–5.x: multi-document transactions + time-series collections + Atlas search), and the intelligent evolution phase (6.x–8.x: vector search + query-encrypted data + serverless).
| Date | Event | Significance |
|---|---|---|
| 2007 | Dwight Merriman, Eliot Horowitz, and Kevin Ryan founded 10gen | Project launch |
| 2009 | MongoDB 1.0 Released (C++-based) | First Open-Source Release |
| 2013 | 10gen Renamed MongoDB Inc. | Brand Spotlight |
| 2014 | Atlas Cloud Service Launched | Cloud-Native Transformation |
| 2018 | Version 4.0 released, supporting multi-document transactions (ACID) | Maximum Dispute Resolution |
| 2020 | Version 5.0 Released, Introducing Time Series Sets and Versioned APIs | IoT Scenario Optimizations |
| Released in July 2023 | Native support for vector search | The AI/LLM Era |
| 2026 | 8.0 Release (Current LTS Candidate) | Latest Stable Release |
(1) 4.1 Origins
(2) 4.2 Key Features of MongoDB 7.x
graph TB
A[MongoDB 7.0 Key Features] --> B[Document Model<br/>BSON + Nesting]
A --> C[Aggregation Pipeline<br/>$facet/$bucket/$lookup]
A --> D[Transactions<br/>Multiple Documents ACID]
A --> E[Change Streams<br/>Real-Time Change Monitoring]
A --> F[Atlas Search<br/>Full Text + Vector Search]
A --> G[Time Series<br/>IoT Scene Optimization]
style A fill:#cce5ff
(3) 4.3 Deployment Methods
Concept Overview: MongoDB supports four deployment options—Atlas cloud service (zero operational overhead), single-node deployment (for development and learning), replica sets (for high availability in production), and sharded clusters (for horizontal scaling of large datasets). The key considerations when choosing a deployment option are: data volume, concurrency, availability requirements, and operational capabilities.
| Deployment Method | Use Cases | Advantages | Data Volume |
|---|---|---|---|
| Atlas Cloud Services | Individuals / Small and Medium-Sized Enterprises / Multinational Corporations | No maintenance required, global deployment, automatic backups | Elastic scaling |
| Self-hosted standalone | Local development and learning | Full control, zero cost | < 1TB |
| Self-hosted Replica Set | Production Environment | High Availability, Automatic Failover | < 8 TB per shard |
| Self-built sharded cluster | Large data volumes, high throughput | Horizontal scaling, petabyte-scale storage | Petabyte-scale |
| Docker Deployment | CI/CD, Local Testing | Quick Start, Reproducible | Development-Level |
▶ Example: Three Ways to Connect to MongoDB
# 1. mongosh Connect Atlas Cloud Services
mongosh "mongodb+srv://cluster0.mongodb.net/mydb" --username alice
# 2. mongosh Connect to a self-hosted local replica set
mongosh "mongodb://localhost:27017/mydb"
# 3. mongosh Connect Docker Container
mongosh "mongodb://192.168.1.100:27017/mydb"
5. Document Model vs. Relational Model
Concept Explanation: The document model and the relational model are two fundamentally different data modeling paradigms. The relational model breaks data down into multiple tables, which are merged at runtime using JOIN operations; the document model embeds related data within a single document and returns it in a single query. Each model has its own advantages and disadvantages—the document model is suitable for scenarios with cohesive data and frequent schema changes, while the relational model is suitable for scenarios with complex relationships between data and strong transactional consistency.
How It Works: The relational model follows a normalized design—each piece of data is stored only once and linked through foreign key references. The document model follows a denormalized design—data that is frequently accessed together is embedded within the same document, trading redundancy for query performance. MongoDB supports document nesting up to 100 levels deep, with a maximum document size of 16 MB, which is sufficient to meet the data modeling needs of most web applications.
(1) Key Differences
graph TB
subgraph Relational Model
T1[users Table<br/>id, name, email] --> J1[JOIN]
T2[orders Table<br/>id, user_id, total] --> J1
T3[order_items Table<br/>id, order_id, product_id] --> J1
J1 --> R[Search Results<br/>Must be merged at runtime]
end
subgraph Document Model
D1[orders Gathering<br/>A document = One order<br/>Includes user + items] --> R2[Search Results<br/>One query returns]
end
style J1 fill:#f8d7da
style R2 fill:#d4edda
(2) Relational vs. MongoDB Terminology Comparison
| Relational Terms | MongoDB Terms | Description |
|---|---|---|
| Database | Database | Database |
| Table | Collection | Table / Collection |
| Row | Document | Row / Document |
| Column | Field | Column / Field |
| Primary Key | _id | Primary Key (Automatically Generated ObjectId) |
| Foreign Key | Reference / Embed | Foreign Key / Embedded Document |
| JOIN | $lookup / embed | Table Join / Document Nesting |
| Index | Index | Index |
| Transaction | Transaction (4.0+) | Transaction |
(3) When to Use MongoDB, and When to Use SQL?
Concept Explanation: MongoDB and SQL are not mutually exclusive—many production systems use both (Polyglot Persistence). MongoDB is suitable for scenarios with frequent schema changes and high write throughput, while SQL is suitable for scenarios requiring strong transactional consistency and complex relationships. The key is to identify which category your business scenario falls into.
| Scenario | Recommendation | Reason |
|---|---|---|
| Frequent schema changes (CMS, product catalog) | ✅ MongoDB | Documents inherently support heterogeneous data |
| High Write Throughput (logs, IoT) | ✅ MongoDB | Document-level atomicity, no transaction locks |
| Complex multi-table joins (ERP, banking) | ⚠️ Use with caution | $lookup is not as mature as JOIN |
| Strong transactional consistency (finance, inventory) | ⚠️ MongoDB 4.0+ | Supported, but with a performance overhead |
| Massive Data OLAP (Data Warehouse) | ❌ Use with caution | ClickHouse / BigQuery are better options |
| Fixed Schema (Orders, Users) | ✅ SQL is also acceptable | Depends on team preferences |
Hybrid Approach: Use MySQL for core business data (users, orders, payments) to ensure transactional consistency; use MongoDB for flexible modeling of behavioral logs, product catalogs, and content data. Synchronize data via message queues or ETL pipelines.
6. MongoDB Atlas Cloud Service
Concept Overview: MongoDB Atlas is an official, fully managed cloud database service available on the three major cloud platforms: AWS, Azure, and Google Cloud. Atlas’s core value lies in its “zero-maintenance” approach—it automatically deploys replica sets, performs backups, handles failover, monitors and alerts, and applies security patches. For teams without a dedicated DBA, Atlas can reduce operational time by 80%.
(1) What is Atlas?
MongoDB Atlas is an fully managed cloud database service provided by MongoDB, available on the three major cloud platforms: AWS, Azure, and Google Cloud.
graph LR
A[Your App] --> B[Atlas Global Clusters]
B --> C[Multi-Region Replicas<br/>Automatic Failover]
B --> D[Automatic Backup<br/>PITR Point-in-Time Recovery]
B --> E[Monitoring Alerts<br/>Performance Optimization Recommendations]
B --> F[Security and Compliance<br/>SCRAM + TLS]
style B fill:#d4edda
(2) Atlas Free Tier
| Resources | Free Allowance |
|---|---|
| Storage | 512 MB |
| RAM | Shared |
| Region | Any |
| Backup | None |
| Duration | Free Forever |
▶ Example 1: Create an Atlas cluster in 5 minutes
1. Visit https://www.mongodb.com/cloud/atlas/register Register
2. Select "Build a Cluster" → "Shared" → "Free"
3. Selecting a Cloud Provider(AWS)and regions(We recommend choosing a location close to the target market.)
4. Cluster Name:Cluster0
5. Click "Create Cluster",Waiting 1-3 minutes
6. In "Database Access" Add a User(Username + Password)
7. In "Network Access" Add IP Whitelist(0.0.0.0/0 Allow all IP)
8. Click "Connect" → "Connect your application" → Get the connection string
(3) Three Cluster Levels
| Tier | Applicable | Price |
|---|---|---|
| M0 Sandbox | Learning, Prototyping | Free |
| M10 / M20 | Small-scale production | Starting at ~$60/month |
| M30 / M40 | Medium-scale production | Starting at ~$300/month |
| M80+ | Large-scale production | $2,000+/month |
| Atlas Serverless | Intermittent load | Pay-as-you-go |
7. An Overview of the MongoDB Ecosystem
(1) Core Components
graph TB
subgraph "MongoDB Ecology"
A[MongoDB Server<br/>Core Database Engine]
B[mongosh<br/>Command-Line Client]
C[MongoDB Compass<br/>GUI Visualization Tools]
D[MongoDB Atlas<br/>Cloud Hosting Services]
E[BI Connector<br/>Tableau / Power BI Integration]
F[Kafka Connector<br/>Real-Time Data Pipeline]
G[mongodump / mongorestore<br/>Backup and Recovery Tool]
end
A --> B
A --> C
A --> D
A --> E
A --> F
A --> G
style A fill:#cce5ff
style D fill:#d4edda
(2) Programming Language-Driven
| Language | Official Drivers | Popular ODMs/ORMs |
|---|---|---|
| JavaScript / Node.js | mongodb |
mongoose (27k⭐) |
| Python | pymongo |
MongoEngine、Flask-MongoEngine |
| Java | mongodb-driver-sync |
Spring Data MongoDB |
| Go | mongo-go-driver |
mgo、Qor |
| PHP | mongodb |
Doctrine MongoDB |
| C# | MongoDB.Driver |
MongoDB.Entities |
| Ruby | mongo |
Mongoid |
(3) De facto standard in the Node.js ecosystem: Mongoose
Concept Overview: Mongoose is the most popular MongoDB ODM (Object Document Modeling) in the Node.js ecosystem, with over 27k stars on GitHub. Building on the native mongodb driver, Mongoose provides advanced features such as schema definition, data validation, middleware, and populate join queries, making MongoDB operations safer and easier to use. The trade-off is a slight performance overhead (which can be disabled via lean()).
| Dimension | Native MongoDB Driver | Mongoose ODM |
|---|---|---|
| Schema Definition | ❌ None | ✅ Type + Validation |
| Data Validation | Manual | Automatic |
| Middleware | ❌ None | ✅ Pre/post hook |
| Joined Query | Manual $lookup | ✅ populate() |
| Performance | Optimal | Slightly lower (can be compensated for using lean()) |
| Learning Curve | Low | Medium |
// mongoose 7.x — Node.js Eco-Friendly Is All the Rage ODM(27k⭐)
const mongoose = require('mongoose');
// 1. Connect to the Database
mongoose.connect('mongodb://localhost:27017/shophub');
// 2. Definition Schema(Data Model)
const productSchema = new mongoose.Schema({
sku: { type: String, required: true, unique: true },
title: { type: String, required: true },
price: { type: Number, required: true, min: 0 },
category: { type: String, enum: ['Electronics', 'Clothing', 'Books'] },
attributes: { type: Object, default: {} },
tags: [String],
stock: { type: Number, default: 0 }
}, { timestamps: true });
// 3. Create Model
const Product = mongoose.model('Product', productSchema);
// 4. CRUD Operation
const phone = await Product.create({
sku: 'PHONE-X-256-BLK',
title: 'Smartphone X 256GB Black',
price: 599.99,
category: 'Electronics',
attributes: { color: 'Black', storage: '256GB' },
tags: ['5g', 'amoled'],
stock: 80
});
▶ Example 2: Installing the Complete MongoDB Toolchain
# 1. Installation mongosh(Command-Line Client)
brew install mongosh # macOS
sudo apt install mongosh # Ubuntu
# 2. Installation MongoDB Compass(GUI Tools)
# Download from https://www.mongodb.com/try/download/compass
# 3. Installation Node.js Driver
npm install mongodb --save
# 4. Installation mongoose(Recommendations)
npm install mongoose --save
# 5. Verify the Installation
mongosh --version
node -e "console.log(require('mongoose').version)"
8. MongoDB and Its Three Major Target Markets
(1) Middle East Market (Arabic)
Use Cases:
- Mobile-first, PWA push notifications
- E-commerce platforms (Noon, Namshi, Amazon Middle East)
- Social media apps (chat history, news feed)
Advantages of MongoDB:
- The document model is suitable for complex, nested comments in Arabic
- High Write Throughput to Handle Major E-commerce Sales Events in the Middle East (Ramadan, White Friday)
- Saudi Arabia Data Center (Atlas me-central-1)
(2) Brazilian Market (Portuguese)
Use Cases:
- E-commerce (Mercado Livre, Americanas)
- Fintech (Nubank, PicPay)
- Package Tracking (Correios)
Advantages of MongoDB:
- A flexible schema that adapts to frequent changes in Brazilian tax regulations
- Processing Order Trajectories Using Time-Series Sets
- São Paulo, Brazil Data Center (Atlas sa-east-1)
(3) Japanese Market (Japanese)
Use Cases:
- Game servers (user data, in-game items)
- E-commerce (Rakuten, Yahoo! Shopping)
- Content platforms (note, Hatena)
Advantages of MongoDB:
- Horizontal scaling supports millions of concurrent users (peak traffic during game launch)
- Change Streams Real-Time Leaderboard
- Tokyo, Japan Data Center (Atlas ap-northeast-1)
9. Suggested Learning Paths
(1) Roadmap for This Tutorial
graph LR
A[Phase 1<br/>MongoDB Getting Started<br/>6 Lessons] --> B[Phase 2<br/>CRUD + mongoose<br/>7 Lessons]
B --> C[Phase 3<br/>Aggregation + Index<br/>7 Lessons]
C --> D[Phase 4<br/>Transactions + Replica Sets + Sharding<br/>5 Lessons]
D --> E[Phase 5<br/>Node.js Practical Application + Comprehensive Projects<br/>5 Lessons]
style A fill:#d4edda
style E fill:#cce5ff
(2) Prerequisite Knowledge
| Must-Have | Recommended |
|---|---|
| ✅ JavaScript Basics (ES6+) | TypeScript |
| ✅ Node.js Basics | Express Framework |
| ✅ Command-Line Operations | Docker |
| ✅ HTTP / REST API | JSON data format |
(3) Estimated Study Time
- Full Course + Hands-On Practice: 40–50 hours
- Getting Started (Phases 1–2): 8–10 hours
- Advanced (Phase 3–4): 14–18 hours
- Comprehensive Project (Phase 5): 12–15 hours
❓ FAQ
populate join queries. It is easier to use than the native mongodb driver, but comes with a slight performance overhead (which can be disabled in production).📖 Summary
- NoSQL databases emerged in response to the explosion of data on the Internet, and MongoDB is a leading example of a document database.
- MongoDB was created by 10gen (now MongoDB Inc.) in 2007 and released as open source in 2009
- The document model is suitable for scenarios with frequent schema changes and high write throughput, while the relational model is suitable for scenarios requiring strong transactions.
- BSON is MongoDB's storage format, which supports more data types than JSON (such as Date and ObjectId).
- MongoDB Atlas is an official cloud-hosted service that offers a 512 MB free tier
- Mongoose is the most popular MongoDB ODM in the Node.js ecosystem (27k⭐)
- This tutorial is divided into 5 phases and consists of 30 lessons; it is estimated to take 40–50 hours to complete.
📝 Exercises
-
Basic Exercise (⭐): Go to mongodb.com/cloud/atlas to sign up for an account, create a free M0 cluster, and successfully connect using
mongosh. -
Basic Exercise (⭐): Execute the
db.runCommand({ ping: 1 })command in the Atlas cluster, take a screenshot of the output, and review the basics of MongoDB connection validation. -
Advanced Exercise (⭐⭐): Use mongosh to execute the following commands:
use shopdb,db.products.insertOne({ sku: "TEST-001", title: "Test Product", price: 9.99 }), anddb.products.find().pretty()to understand MongoDB’s implicit database/collection creation. -
Advanced Question (⭐⭐): Read the "What is NoSQL?" section of the official MongoDB documentation (search for the keyword), and list one real-world use case for each of the four major NoSQL families (key-value, document, column-oriented, and graph).
-
Challenge (⭐⭐⭐): Compare the two Node.js ORMs—MongoDB (Mongoose) and MySQL (Sequelize)—and implement code for "creating a user table/collection (with 5 fields)" for each, noting the differences in API style between the two ORMs.