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



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 products table 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.

JAVASCRIPT
// 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:

(2) The Four Major Families of NoSQL

Key Points Analysis:

  1. 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.
  2. The document database is the most versatile—it supports nesting, arrays, and secondary indexes, making it suitable for most web applications.
  3. Column-oriented databases excel at data ingestion—data is stored by column family, making them suitable for time series and log data
  4. 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
100%
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

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

100%
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

BASH
# 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

100%
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.

100%
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

TEXT
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

100%
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 MongoEngineFlask-MongoEngine
Java mongodb-driver-sync Spring Data MongoDB
Go mongo-go-driver mgoQor
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
JAVASCRIPT
// 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

BASH
# 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:

Advantages of MongoDB:

(2) Brazilian Market (Portuguese)

Use Cases:

Advantages of MongoDB:

(3) Japanese Market (Japanese)

Use Cases:

Advantages of MongoDB:



9. Suggested Learning Paths

(1) Roadmap for This Tutorial

100%
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


❓ FAQ

Q Is MongoDB free?
A MongoDB Community Edition (on-premises) is completely free and open source (under the SSPL license). MongoDB Atlas offers a 512 MB cluster that is free forever. The commercial version (Enterprise Advanced) is billed based on cluster size.
Q Which should I choose, MongoDB or MySQL?
A It depends on the business scenario. Fixed schema + strong transactions (e.g., orders, ERP) → MySQL; frequent schema changes + high write volumes (e.g., CMS, product catalogs, logs) → MongoDB. You can also use a hybrid approach (MySQL for core business data + MongoDB for user behavior logs).
Q Do I need to know SQL to learn MongoDB?
A No. This tutorial covers document database concepts from scratch. However, if you have a basic understanding of SQL, you’ll be able to grasp MongoDB concepts such as the $lookup (similar to JOIN) and $group (similar to GROUP BY) in the aggregation pipeline more quickly.
Q What is the relationship between a MongoDB "document" and JSON?
A MongoDB documents are stored in BSON (Binary JSON) format, which supports more data types than JSON (such as Date, ObjectId, and Decimal128). However, the syntax is almost identical to JSON, so there is no learning curve for front-end developers.
Q How large of a dataset can MongoDB store?
A The maximum size for a single document in MongoDB is 16 MB (design philosophy: avoid storing very large documents). A single collection can store petabytes of data (through sharding). On Atlas, the largest cluster supports 4,096 shards, with each shard capable of storing 32 TB.
Q What is Mongoose? Why use it?
A Mongoose is the most popular MongoDB ODM in the Node.js ecosystem (27k⭐). It offers advanced features such as schema definition, data validation, middleware, and 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


📝 Exercises

  1. Basic Exercise (⭐): Go to mongodb.com/cloud/atlas to sign up for an account, create a free M0 cluster, and successfully connect using mongosh.

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

  3. Advanced Exercise (⭐⭐): Use mongosh to execute the following commands: use shopdb, db.products.insertOne({ sku: "TEST-001", title: "Test Product", price: 9.99 }), and db.products.find().pretty() to understand MongoDB’s implicit database/collection creation.

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

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

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏