The most widely used NoSQL/big data document database
π MongoDB Complete Guide
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
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.
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. Insertdb.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. Deletedb.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 indexdb.users.createIndex({ age: 1 });// 2. Create a compound indexdb.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 plandb.users.find({ age: 30 }).explain("executionStats");
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: 300000db.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 hintdb.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
// 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 rangedb.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 skipsdb.orders.find().sort({ _id: 1 }).skip(200000).limit(20) // totalKeysExamined: 200020db.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 collectiondb.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 indexdb.orders.aggregate([{ $indexStats: {} }])
What explain shows
Meaning
Response
COLLSCAN
Reads the whole collection.
Create an index that matches the condition.
IXSCAN β FETCH
Finds through the index, then reads the documents.
The usual good plan.
PROJECTION_COVERED
Answers from the index alone.
Reads the least.
A SORT stage is present
Index order could not be used, so it sorts in memory.
Put the sort field in the index (ESR order).
totalDocsExamined β« nReturned
Most of the documents read were discarded.
An index that narrows the condition further is needed.
totalKeysExamined β« nReturned
The index was scanned widely.
Reorder the index fields to match the condition.
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 model
Structure
Main purpose
Replica Set
One Primary node + several Secondary nodes
High availability (HA), data redundancy, automatic failover when the Primary goes down
Sharding
Mongos routers, Config servers, Shard nodes
Horizontal 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 rightsuse 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 statedb.runCommand({ connectionStatus: 1 });
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 point
Question to ask
Practical guideline
Boundaries
Which parts of the MongoDB code are most likely to change?
Separate input/output, configuration, external integrations, and the core rules.
State
Where is state created and where does it go away?
Make the owner and lifecycle of state visible in the code.
Failure
What 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.
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 axis
How to verify
Definition of done
Correctness
Automate the normal/failure cases.
The core scenarios pass reproducibly.
Regression prevention
When fixing a bug, leave the same case behind as a test.
The same failure is not deployed again.
Operability
Check 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.