Skip to main content
AIDevOps
  • Learn
  • Learning Paths
  • Practice
  • Open Source
  • Books
  • Engineering

    AI DevOpsThe full map of building and operating AI servicesLLMOpsLLM deployment Β· evaluation Β· observabilityHands-on ProjectsBuild AI Agent projects

    Knowledge

    DocsTechnical documentationBlogEngineering articlesPloggerDevelopment log feed

    Validate

    Certification3-level skills certification Β· coming soon
AI Models
LlamaTutorial|MistralTutorial|GemmaTutorial|DeepSeekTutorial|QwenTutorial
πŸ’Ύ Database
DB Intro & RoadmapCore SQLOracleMySQLPostgreSQL|MongoDBVector DB
πŸ€– AI Applied Development
Applied AI Intro & RoadmapHugging FaceLangChainLlamaIndexLLMOps|LangGraphMCPMulti-AgentAgent Evaluation
🧠 AI Core
AI Intro & RoadmapML FundamentalsLLM Fundamentals|Python AIC++|PyTorchTensorFlowJAX
🧠 AI Agent Development
Finance AI AgentLLM API ServerStock Investing AgentAIOps AI AgentEducation AI AgentCoding AI Agent
🌱 Spring Cloud
Spring Intro & RoadmapSpring Cloud GatewaySpring BootJava|Spring AISpring SecuritySpring BatchSpring JPA
🐳 DevOps
DevOps Intro & RoadmapLinuxDockerCI/CD|Kubernetes BasicsK8s AdvancedPrometheusGrafana
🧱 Infrastructure
Infrastructure Intro & RoadmapNginxRedis
☁️ Cloud
Cloud Intro & RoadmapAWSGCPAzureNCPCloudflare
🎨 Frontend
Frontend Intro & RoadmapJavaScriptTypeScript|ReactNext.js|VueNuxt|Electron
πŸ“± Mobile
Mobile Intro & RoadmapKotlinAndroidFlutter
βš™οΈ Backend
Backend Intro & RoadmapPython BasicsFastAPIDjangoFlask|CGoGinNode.js
πŸ§ͺ Testing
k6JMeternGrinder
AIDevOps

Engineering AI. From Code to Production.
An engineering learning platform for building and operating AI and AI Agents

Learn

  • All Guides
  • Learning Paths
  • AI Tutorial
  • Practice
  • Books

Resources

  • AI DevOps
  • LLMOps
  • Hands-on Projects
  • Docs
  • Blog
  • Plogger
  • Open Source
  • Certification (coming soon)

Start Here

  • AI Core Roadmap
  • AI Applied Development Roadmap
  • Spring Cloud Roadmap
  • DevOps Roadmap
  • Infrastructure Roadmap

Β 

  • Cloud Roadmap
  • Frontend Roadmap
  • Mobile Roadmap
  • Backend Roadmap
  • Database Roadmap
Β© 2026 AIDevOps. All rights reserved.
Terms of ServicePrivacy PolicySitemaptestforge.kr
  1. Home
  2. Learn
  3. Database
  4. MongoDB
The most widely used NoSQL/big data document database

πŸƒ MongoDB Complete Guide

Visitors

Learn MongoDB, the leading NoSQL database that overcomes the limits of relational databases. Covers the schemaless document model (BSON), CRUD, handling complex data pipelines with the Aggregation Pipeline, and Sharding/Replica Set setups for high-volume workloads.

  • Intermediate
  • Updated Oct 10, 2026
  • ~6 min read
  • 10 sections
  • 9 code examples
πŸƒ
Loading unstructured/semi-structured big dataRapid service prototypingHighly available distributed environmentsReal-time, high-volume log collection

Related frameworks & environments

πŸ’ΎCore SQLβ†’πŸŸ’Node.jsβ†’πŸPython Basicsβ†’

Contents

0 / 13
  1. How to use this guide
  2. Architecture diagrams
  3. The document-oriented model and BSON
  4. MongoDB CRUD commands
  5. Aggregation pipeline
  6. Index tuning & TTL
  7. Query tuning β€” explain and hint
  8. Replica Set & Sharding
  9. MongoDB role-based access control (RBAC)
  10. MongoDB design
  11. Operating standards
  12. Verification strategy
  13. Frequently asked questions
Contents 13 sections
  1. How to use this guide
  2. Architecture diagrams
  3. The document-oriented model and BSON
  4. MongoDB CRUD commands
  5. Aggregation pipeline
  6. Index tuning & TTL
  7. Query tuning β€” explain and hint
  8. Replica Set & Sharding
  9. MongoDB role-based access control (RBAC)
  10. MongoDB design
  11. Operating standards
  12. Verification strategy
  13. Frequently asked questions

How to use this guide

How to read it

Understanding MongoDB as a real-world workflow

Learn MongoDB, the leading NoSQL database that overcomes the limits of relational databases. Covers the schemaless document model (BSON), CRUD, handling complex data pipelines with the Aggregation Pipeline, and Sharding/Replica Set setups for high-volume workloads. Rather than listing concepts, this guide is organized so you can follow the content in the order you have to make decisions on a real project.

Key perspective

Databases

Alongside query syntax, look at schema design, indexes, transactions, permissions, and backups from an operations perspective.

Loading unstructured/semi-structured big dataRapid service prototypingHighly available distributed environmentsReal-time, high-volume log collection

Architecture diagrams

To make what you read stick, it helps to capture the flow as a picture first. The two diagrams below are reference maps you can keep coming back to while learning MongoDB.

Learning flow

Rendering diagram…

Architecture view

Rendering diagram…

The document-oriented model and BSON

When you first open MongoDB, the big picture matters more than individual commands. This section starts with the problems the concepts ahead were created to solve.

MongoDB stores data in collections not as table rows but as documents in BSON (Binary JSON), the binary form of JSON. There is no fixed schema, so documents in a collection can have different structures.
document_example.jsonJSON
{
  "_id": "507f1f77bcf86cd799439011",
  "name": "Jane Doe",
  "age": 28,
  "skills": ["JavaScript", "Python"],
  "contact": {
    "email": "jane@example.com",
    "phone": "010-1234-5678"
  },
  "created_at": "2026-06-13T02:00:00Z"
}

MongoDB CRUD commands

Here you look at MongoDB CRUD commands alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.

The SELECT, INSERT, UPDATE, and DELETE statements of SQL map, through MongoDB shell commands, to method calls on the collection object.
crud_operations.jsJAVASCRIPT
// 1. Insert
db.users.insertOne({ name: "Alice", age: 30, active: true });

// 2. Read (active users aged 25 or over)
db.users.find({ age: { $gte: 25 }, active: true });

// 3. Update (increase the age of the user named Alice by 1)
db.users.updateOne({ name: "Alice" }, { $inc: { age: 1 } });

// 4. Delete
db.users.deleteOne({ name: "Alice" });

Aggregation pipeline

Here you look at Aggregation pipeline alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.

The MongoDB Aggregation framework performs complex statistical aggregation by transforming, filtering, and grouping data stage by stage along a pipeline. It is freer and more powerful than GROUP BY and HAVING in SQL.
aggregation.jsJAVASCRIPT
db.orders.aggregate([
  // Stage 1: filter orders in the completed state
  { $match: { status: "completed" } },
  
  // Stage 2: group by customer (customerId) and sum the total amount
  { $group: { _id: "$customerId", totalAmount: { $sum: "$price" }, count: { $sum: 1 } } },
  
  // Stage 3: keep only groups whose total order amount is 100 or more
  { $match: { totalAmount: { $gte: 100 } } },
  
  // Stage 4: sort by total order amount, descending
  { $sort: { totalAmount: -1 } }
]);

Index tuning & TTL

Here you look at Index tuning & TTL alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.

Indexes are the key to fast read queries, and beyond compound indexes MongoDB offers distinctive index features such as the TTL (Time-to-Live) index, which deletes data automatically after a set time.
indexing.jsJAVASCRIPT
// 1. Create a single-field index
db.users.createIndex({ age: 1 });

// 2. Create a compound index
db.users.createIndex({ active: 1, age: -1 });

// 3. TTL index (automatic deletion from the logs collection after 30 days (2592000 seconds))
db.logs.createIndex({ created_at: 1 }, { expireAfterSeconds: 2592000 });

// 4. Check the execution plan
db.users.find({ age: 30 }).explain("executionStats");

Tip

When designing a compound index, it is best to follow the ESR rule: equality fields first, then sort fields, and range fields last.

Query tuning β€” explain and hint

Here you look at Query tuning β€” explain and hint alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.

How a query runs in MongoDB is checked with explain("executionStats"). There are three numbers to read: documents returned (nReturned), index keys examined (totalKeysExamined), and documents examined (totalDocsExamined). The closer the three are, the better the query; when the examined counts are far larger than the returned count, the index does not fit.

The numbers below were run on MongoDB 8.2 with 300,000 order documents.

With and without an indexJAVASCRIPT
db.orders.find({ customerId: 42 }).explain("executionStats")

// Without an index
//   winningPlan: COLLSCAN                       ← reads the whole collection
//   nReturned: 30, totalKeysExamined: 0, totalDocsExamined: 300000

db.orders.createIndex({ customerId: 1 })

// After creating the index
//   winningPlan: FETCH <- IXSCAN (customerId_1)
//   nReturned: 30, totalKeysExamined: 30, totalDocsExamined: 30
Order in a compound index β€” the ESR rule (Equality β†’ Sort β†’ Range)JAVASCRIPT
// "20 PENDING orders with an amount of 400 or more, newest first"
const query = db.orders.find({ status: "PENDING", amount: { $gte: 400 } })
                       .sort({ createdAt: -1 }).limit(20)

// An index in the order equality (status) β†’ sort (createdAt) β†’ range (amount)
db.orders.createIndex({ status: 1, createdAt: -1, amount: 1 })
//   winningPlan: LIMIT <- FETCH <- IXSCAN       ← no sort stage
//   nReturned: 20, totalKeysExamined: 92, totalDocsExamined: 20

// Forcing an index in the order equality β†’ range β†’ sort with hint
db.orders.createIndex({ status: 1, amount: 1, createdAt: -1 })
query.hint({ status: 1, amount: 1, createdAt: -1 })
//   winningPlan: FETCH <- SORT <- IXSCAN        ← a separate in-memory sort
//   nReturned: 20, totalKeysExamined: 5400, totalDocsExamined: 20
Covered queries, regular expressions, paginationJAVASCRIPT
// When every needed field is in the index, no document is read (_id has to be excluded)
db.orders.find({ customerId: 42 }, { _id: 0, customerId: 1, createdAt: 1 })
//   winningPlan: PROJECTION_COVERED <- IXSCAN (customerId_1_createdAt_-1)
//   nReturned: 30, totalKeysExamined: 30, totalDocsExamined: 0

// Regular expressions: the prefix has to be fixed to narrow the index range
db.orders.find({ status: /NCEL/ })     // totalKeysExamined: 300000  (scans the whole index)
db.orders.find({ status: /^CANC/ })    // totalKeysExamined: 3001

// Deep pages: skip reads as much as it skips
db.orders.find().sort({ _id: 1 }).skip(200000).limit(20)             // totalKeysExamined: 200020
db.orders.find({ _id: { $gt: 200000 } }).sort({ _id: 1 }).limit(20)  // totalKeysExamined: 20
hint and the profilerJAVASCRIPT
// Specify an index (by index name or key pattern)
db.orders.find({ customerId: 42, status: "DONE" }).hint({ customerId: 1 })

// Read everything without an index (for comparison)
db.orders.find({ customerId: 42 }).hint({ $natural: 1 })
//   winningPlan: COLLSCAN, totalDocsExamined: 300000

// Record slow operations: operations over 100ms go to the system.profile collection
db.setProfilingLevel(1, { slowms: 100 })
db.system.profile.find({ ns: "shop.orders" }).sort({ ts: -1 }).limit(5)
//   { op: "query", planSummary: "COLLSCAN", docsExamined: …, keysExamined: 0, nreturned: …, millis: … }

// Usage count per index
db.orders.aggregate([{ $indexStats: {} }])
What explain showsMeaningResponse
COLLSCANReads the whole collection.Create an index that matches the condition.
IXSCAN β†’ FETCHFinds through the index, then reads the documents.The usual good plan.
PROJECTION_COVEREDAnswers from the index alone.Reads the least.
A SORT stage is presentIndex order could not be used, so it sorts in memory.Put the sort field in the index (ESR order).
totalDocsExamined ≫ nReturnedMost of the documents read were discarded.An index that narrows the condition further is needed.
totalKeysExamined ≫ nReturnedThe index was scanned widely.Reorder the index fields to match the condition.

Tip

  • Use hint only after explain confirms the optimizer is choosing wrongly. As in the example above, a hint can also force a worse plan.
  • ESR is a starting point, not an absolute rule. When the range condition cuts the result down a great deal, putting the range before the sort can be better. Decide by comparing the explain numbers.
  • Running the profiler at level 2 (record every operation) in production adds heavy load. Use level 1 with a slowms threshold.
  • In-memory sorts have a size limit, so sorting a large result without an index fails or spills to disk. The rule is to solve sorting with an index.

Replica Set & Sharding

Replica Set & Sharding is a point where the options diverge. Using the table to compare what each approach is for and how it differs in operation makes later decisions much easier.

High-volume web service architectures handle heavy traffic by adopting Replica Sets for failover and the distributed sharding architecture for unlimited horizontal scaling.
Architecture modelStructureMain purpose
Replica SetOne Primary node + several Secondary nodesHigh availability (HA), data redundancy, automatic failover when the Primary goes down
ShardingMongos routers, Config servers, Shard nodesHorizontal distribution of writes/reads, partitioned storage of terabyte-scale big data

MongoDB role-based access control (RBAC)

Here you look at MongoDB role-based access control (RBAC) alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.

MongoDB provides role-based security (RBAC): after a user goes through authentication when connecting to the database, the scope of permitted actions and resources is limited according to the roles mapped to that user.
mongo_rbac.jsJAVASCRIPT
// 1. Switch to the admin database and create a dedicated user with restricted read/write rights
use admin;

db.createUser({
  user: "app_service_user",
  pwd: "securePassword123",
  roles: [
    // grant read and write on the mydb database
    { role: "readWrite", db: "mydb" },
    // grant index creation and profiler management on the mydb database
    { role: "dbAdmin", db: "mydb" }
  ]
});

// 2. The main built-in roles of MongoDB
// - read: the right to read data
// - readWrite: the right to read and add/modify/delete data
// - dbAdmin: administrative rights such as viewing schema information, creating indexes, and statistics
// - userAdmin: the right to create users and grant/revoke privileges (high security risk)
// - dbOwner: includes everything in readWrite, dbAdmin, and userAdmin
// - root: admin DB only; control over the whole cluster and every database

// 3. View my privilege state
db.runCommand({ connectionStatus: 1 });

Tip

  • MongoDB has authentication disabled (noauth) by default, so account security applies only after you enable security.authorization: enabled in the mongod.conf configuration file and restart the server.
  • For the account the application connects with, always avoid the root and dbOwner roles; granting only the readWrite role limited to a specific DB is the safe choice.

MongoDB practical design

MongoDB practical design is a point where the options diverge. Using the table to compare what each approach is for and how it differs in operation makes later decisions much easier.

MongoDB design centers on embedded document design together with defining RBAC roles at the cluster and database level. The users and privilege boundaries of the admin database and the ordinary service databases must be isolated.
Decision pointQuestion to askPractical guideline
BoundariesWhich parts of the MongoDB code are most likely to change?Separate input/output, configuration, external integrations, and the core rules.
StateWhere is state created and where does it go away?Make the owner and lifecycle of state visible in the code.
FailureWhat does the caller receive on failure?Decide the timeout, fallback, and error contract first.

MongoDB operating standards

This section covers MongoDB operating standards from a practical perspective. Instead of memorizing the concept, focus on the situations in which you would reach for it.

Along with monitoring the WiredTiger engine cache and load balancing across Shard nodes, enforce configuration management that guarantees mongod.conf security authentication (authorization: enabled) is turned on in production.

Tip

  • WiredTiger cache dirty/eviction ratio
  • Check that security.authorization is enabled
  • Verify effective roles from connectionStatus
  • Whether the indexes fit in RAM

MongoDB verification strategy

MongoDB verification strategy is a point where the options diverge. Using the table to compare what each approach is for and how it differs in operation makes later decisions much easier.

Beyond checking Aggregation Pipeline optimization, run the connectionStatus shell command and verify that the roles array of the current session neither lacks what it needs nor includes unnecessary dbOwner or root privileges.
Quality axisHow to verifyDefinition of done
CorrectnessAutomate the normal/failure cases.The core scenarios pass reproducibly.
Regression preventionWhen fixing a bug, leave the same case behind as a test.The same failure is not deployed again.
OperabilityCheck the logs, metrics, and alerts.There is a path for tracing the cause when a problem occurs.

MongoDB: frequently asked questions

When is MongoDB a good fit?

When data is read together as a document, and when items differ slightly in structure or change often. Product catalogs, content, and event records are examples. Business data that joins many tables and needs strict consistency fits a relational database better.

How do I decide between embedding data in one document and referencing it?

Data that is read and changed together goes in one document, and data that is queried independently or keeps growing goes in a separate collection and is referenced. A single document has a size limit, so do not keep an array that grows without bound inside a document. The deciding factor is how the application reads the data.

Can I use transactions in MongoDB?

A change to a single document is atomic, and in a replica set transactions across several documents are supported too. Multi-document transactions have a cost, so the first choice is a design that keeps data that changes together in one document and needs no transaction.

← Previous guidePostgreSQLNext guide β†’Vector DB