MongoDB Tutorial
Learn MongoDB step by step: 70 lessons in 14 chapters with examples, quizzes, diagrams and projects.
Start learning →
of lessons completed
Getting started
- What Is MongoDB? Learn what MongoDB is, how documents, collections and databases fit together, how it differs from relational databases, and when it is the right choice.
- Installing MongoDB and Using mongosh Install MongoDB locally, in Docker or on Atlas, connect with mongosh, learn the basic shell commands and read connection strings, with runnable stand-ins.
- MongoDB Compass, the Graphical Client Use MongoDB Compass to connect to a server, browse and edit documents, filter with the query bar, analyze schema, build aggregation pipelines, manage indexes and check validation rules.
- The Practice Engine Used in This Tutorial Meet the small JavaScript engine behind this tutorial's runnable examples: how it matches filters, updates documents and runs pipelines, and what it does not emulate.
Documents and BSON
- Documents, JSON and Field Types Learn how MongoDB documents are structured: fields, nested objects, arrays, field-name rules, the 16 MB size limit and how a document compares with a table row.
- BSON Types Learn the BSON types MongoDB stores: strings, numbers, dates, ObjectId, null versus missing, common type pitfalls and the $type operator, with runnable stand-ins.
- _id and ObjectId Understand the MongoDB _id rule, how an ObjectId is built from a timestamp, random value and counter, and when to use custom ids, UUIDs or natural keys.
- Capped Collections and Managing Databases and Collections Create, list, rename and drop MongoDB collections, read dbStats and collStats, and learn when to use a capped collection or a TTL index for logs and other rolling data.
CRUD: create and read
- Inserting Documents Learn how to insert documents in MongoDB: insertOne, insertMany, generated _id values, ordered vs unordered inserts, duplicate key errors and write results.
- Finding Documents Learn how MongoDB find and findOne work: filter documents, equality matching on several fields, the empty filter, matching array fields and how cursors behave.
- Projection: Choosing Fields Learn MongoDB projection: include or exclude fields, handle _id, project nested fields, trim arrays with $slice and $elemMatch, and avoid mixing rules.
- Sorting, Limiting and Skipping Learn MongoDB sort, limit and skip: ascending and descending order, tie-breaking, pagination with skip, why large skips are slow and range-based pagination.
- Cursors: Iterating, Batching and Timeouts How MongoDB cursors work: iterate with hasNext, next, forEach and toArray, tune batchSize, avoid cursor timeouts, understand exhaustion and tailable cursors, and count correctly.
- Querying Nested Fields and Arrays Learn to query nested documents and arrays in MongoDB: dot notation, matching array elements, positions, exact array matches and arrays of subdocuments.
Query operators
- Comparison Operators Learn MongoDB comparison operators: $eq, $ne, $gt, $gte, $lt, $lte, $in and $nin, range queries, and how type bracketing limits matches across types.
- Logical Operators Combine MongoDB conditions with implicit AND, $and, $or, $nor and $not. Learn the duplicate-key trap, how $not treats missing fields and how to nest filters.
- Element and Evaluation Operators Test whether a field exists or has a given BSON type, match text with $regex, compare two fields with $expr, use $mod, and see $jsonSchema in queries.
- Bitwise Query Operators Query integer flag fields with $bitsAllSet, $bitsAnySet, $bitsAllClear and $bitsAnyClear, choose between bitmasks and bit positions, and set or clear bits with the $bit update operator.
- Array Query Operators Query MongoDB arrays with $all, $size and $elemMatch. Learn why two conditions can match different array elements and how $elemMatch fixes it.
- Text Matching and Regular Expressions Match text in MongoDB with $regex, learn which patterns can use an index, and compare it with text indexes, $text and Atlas Search for real search features.
CRUD: update and delete
- Updating Documents Change MongoDB documents with updateOne and updateMany. Learn $set, $unset, $inc, $mul, $min, $max, $rename, $currentDate and matched versus modified counts.
- Updating Arrays Change MongoDB arrays in place with $push, $pull, $addToSet, $pop, $each, $position and $slice, then update single elements with $, $[] and $[id].
- Upserts, Replace and findAndModify Insert-or-update in one call with upsert and $setOnInsert, swap whole documents with replaceOne, and update-and-return atomically with findOneAndUpdate.
- Deleting Documents Remove data with deleteOne and deleteMany, know when drop is better, use soft deletes, preview TTL expiry and build safe delete habits.
- Bulk Writes Send many inserts, updates and deletes in one request with bulkWrite, understand ordered vs unordered errors, and batch large imports.
Aggregation pipeline
- The Aggregation Pipeline Learn how the MongoDB aggregation pipeline passes documents through stages such as $match, $project, $sort and $limit, and why stage order matters.
- Grouping with $group Summarize documents with the $group stage: choose an _id key, use $sum, $avg, $min, $max, $first, $push and $addToSet, count, and group by several fields.
- Expressions and Operators Compute values inside pipelines: field paths, $add and $multiply, $cond and $switch, string operators, $ifNull, date operators and $addFields.
- Working with Arrays in Pipelines Learn how to flatten arrays with $unwind and reshape them with $map, $filter, $reduce, $size and $arrayElemAt inside MongoDB aggregation pipelines.
- Joining with $lookup Learn how $lookup joins collections in MongoDB aggregation, how the pipeline form works, what joins cost, and when embedding data is the better design.
- $facet, $bucket and Other Stages Meet the utility stages of MongoDB aggregation: $facet, $bucket, $bucketAuto, $count, $sortByCount, $sample, $replaceRoot, $unionWith, $merge and $out.
- Window Functions and Advanced Aggregation Learn MongoDB window functions with $setWindowFields: running totals, moving averages, ranking, plus $densify and $fill, compared with SQL windows.
- Map-Reduce and Why Pipelines Replaced It Learn how MongoDB's legacy mapReduce works (map, reduce, finalize, out), why it is deprecated, and how to rewrite each job with $group, $merge, $accumulator and $function.
- Aggregation Performance and Explain Make MongoDB aggregation pipelines fast: put $match first, use indexes, respect the 100 MB stage limit, read explain output and learn what the optimizer does.
Indexes and performance
- How Indexes Work Understand MongoDB indexes: collection scans versus index scans, the B-tree idea, the automatic _id index, createIndex, and what indexes cost on writes.
- Index Types A tour of MongoDB index types: single field, compound, multikey, text, hashed, geospatial, wildcard, plus partial, sparse, TTL, unique and hidden options.
- Geospatial Data and Queries Store locations as GeoJSON, create a 2dsphere index, and query with $near, $geoWithin, $geoIntersects and the $geoNear stage to find places nearby, inside an area or crossing a route.
- Designing Compound Indexes Learn how to order fields in a MongoDB compound index with the ESR rule, the prefix rule, sort direction and covered queries, with runnable demos.
- explain() and the Profiler Read MongoDB explain() output, spot COLLSCAN and in-memory sorts, compare docsExamined with nReturned, and find slow queries with the profiler and currentOp.
- Common Performance Pitfalls Avoid the MongoDB habits that make queries slow: unbounded arrays, large skips, unanchored regex, negations, too many indexes, small RAM and fat results.
Schema design
- Embedding vs Referencing Decide when to embed related data in one MongoDB document and when to reference it from another collection, using access patterns, atomicity and size limits.
- Schema Design Patterns Learn eight MongoDB schema design patterns: subset, bucket, computed, extended reference, outlier, polymorphic, attribute and schema versioning, with runnable demos.
- Modeling Relationships Model one-to-many and many-to-many links, trees with parent references and materialized paths, and graph-like data in MongoDB, including $graphLookup.
- Schema Validation Enforce document shape in MongoDB with a $jsonSchema validator, choose validationLevel and validationAction, change rules with collMod, and validate in code too.
- Case Study: Modeling an Online Shop Design a MongoDB schema for an online shop step by step: list access patterns, shape products, orders and reviews, and compare the result with a relational design.
Transactions and consistency
- Atomicity and Single-Document Writes Understand why a single-document write in MongoDB is atomic, how atomic operators avoid race conditions, and how optimistic concurrency with a version field works.
- Multi-Document Transactions Learn how multi-document ACID transactions work in MongoDB: sessions, withTransaction, retrying TransientTransactionError, the cost and limits, and when to avoid them.
- Read and Write Concerns Tune durability and visibility in MongoDB: write concern w, j and wtimeout, majority writes, read concern levels, read preference and causal consistency.
- Change Streams and Real-Time Updates Learn MongoDB change streams: watch() a collection, read insert, update and delete events, filter with a pipeline, resume after a crash and keep caches in sync.
Replication, sharding and operations
- Replica Sets Understand MongoDB replica sets: primary and secondaries, the oplog, elections and failover, arbiters, rollbacks and replica set connection strings.
- Sharding Learn MongoDB sharding: shards, mongos and config servers, choosing a shard key, ranged vs hashed sharding, chunks, the balancer, zones and resharding.
- Backup, Restore and Import/Export Back up and restore MongoDB: mongodump and mongorestore, mongoexport and mongoimport, filesystem snapshots, point-in-time recovery and Atlas backups.
- Storage Engine Internals: WiredTiger, Journaling and Checkpoints Understand MongoDB's WiredTiger storage engine: document-level concurrency, the cache and its sizing, compression, the journal, checkpoints and how a crash is recovered.
- MongoDB Atlas Overview A tour of MongoDB Atlas: clusters and tiers, network access, database users, monitoring, Atlas Search, Vector Search, Data Federation and how pricing works.
Drivers and applications
- Using MongoDB from Node.js Use MongoDB from Node.js with the official driver: MongoClient and connection pooling, CRUD with async/await, cursors, error handling and good habits.
- Using MongoDB from Python Use MongoDB from Python with PyMongo: MongoClient, insert, find, update, delete, cursors, ObjectId handling and a quick look at Motor for async code.
- MongoDB from Django, and a Node Signup and Login Flow Connect Django to MongoDB with the MongoDB backend or PyMongo, then build an Express signup and login flow with a unique email index, hashed passwords, sessions and safe error handling.
- Mongoose and ODMs Learn what an ODM like Mongoose adds to MongoDB: schemas, models, validation, middleware, populate and lean queries, and when it helps or gets in the way.
Security
- Authentication and Role-Based Access Secure MongoDB with users, SCRAM authentication and roles: enable access control, grant least privilege, build custom roles and see how x.509 and LDAP fit in.
- Securing a Deployment Harden a MongoDB deployment: bind to private networks, require TLS, encrypt data at rest and in fields, audit access and keep tested backups. Includes a checklist.
- NoSQL Injection and Safe Queries Understand NoSQL injection in MongoDB: how $ne and $gt in a JSON body bypass a login, why $where is risky, and how to validate, coerce and sanitize input safely.
Projects
- Project: A Task Tracker Data Layer Build the data layer of a task tracker: a document model, validation, CRUD functions, queries by status and due date, and indexes, on the practice engine.
- Project: Blog with Comments and Tags Build the data layer of a blog in MongoDB: decide what to embed, query by tags, keep comment counts correct with aggregation, and paginate posts.
- Project: Sales Analytics Pipelines Turn raw orders into business reports with MongoDB aggregation: revenue by month and category, top customers, cohorts, $lookup joins and a $facet dashboard.
- Project: Event Logging with Bucketing and TTL Store a stream of sensor events efficiently in MongoDB with the bucket pattern, roll them up into daily summaries, expire old data with TTL, and meet time-series collections.
- Project: Inventory with Safe Concurrent Updates Keep stock counts correct when many users act at once: atomic decrements, optimistic locking with a version field, order transactions and idempotent retries.
Practice and wrap-up
- Practice: Query and Update Exercises Twenty hands-on MongoDB exercises on find, comparison and logical operators, arrays, sorting, pagination and updates, each with a full runnable solution.
- Practice: Aggregation Exercises Fifteen MongoDB aggregation exercises, from $group and $project to $unwind, $lookup and $facet, each with a full runnable pipeline solution and an explanation.
- MongoDB Interview Questions Prepare for MongoDB interviews with concise answers on concepts, indexing, schema design, aggregation, transactions, replication and sharding, plus a quiz.
- MongoDB Cheat Sheet A one-page MongoDB reference for mongosh: CRUD, query and update operators, aggregation stages, indexes, explain and admin commands, with short examples.