Skip to content
Tutorials Center
My learning

Topics

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

  1. 1 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.
  2. 2 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.
  3. 3 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.
  4. 4 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

  1. 5 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.
  2. 6 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.
  3. 7 _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.
  4. 8 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

  1. 9 Inserting Documents Learn how to insert documents in MongoDB: insertOne, insertMany, generated _id values, ordered vs unordered inserts, duplicate key errors and write results.
  2. 10 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.
  3. 11 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.
  4. 12 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.
  5. 13 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.
  6. 14 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

  1. 15 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.
  2. 16 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.
  3. 17 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.
  4. 18 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.
  5. 19 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.
  6. 20 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

  1. 21 Updating Documents Change MongoDB documents with updateOne and updateMany. Learn $set, $unset, $inc, $mul, $min, $max, $rename, $currentDate and matched versus modified counts.
  2. 22 Updating Arrays Change MongoDB arrays in place with $push, $pull, $addToSet, $pop, $each, $position and $slice, then update single elements with $, $[] and $[id].
  3. 23 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.
  4. 24 Deleting Documents Remove data with deleteOne and deleteMany, know when drop is better, use soft deletes, preview TTL expiry and build safe delete habits.
  5. 25 Bulk Writes Send many inserts, updates and deletes in one request with bulkWrite, understand ordered vs unordered errors, and batch large imports.

Aggregation pipeline

  1. 26 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.
  2. 27 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.
  3. 28 Expressions and Operators Compute values inside pipelines: field paths, $add and $multiply, $cond and $switch, string operators, $ifNull, date operators and $addFields.
  4. 29 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.
  5. 30 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.
  6. 31 $facet, $bucket and Other Stages Meet the utility stages of MongoDB aggregation: $facet, $bucket, $bucketAuto, $count, $sortByCount, $sample, $replaceRoot, $unionWith, $merge and $out.
  7. 32 Window Functions and Advanced Aggregation Learn MongoDB window functions with $setWindowFields: running totals, moving averages, ranking, plus $densify and $fill, compared with SQL windows.
  8. 33 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.
  9. 34 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

  1. 35 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.
  2. 36 Index Types A tour of MongoDB index types: single field, compound, multikey, text, hashed, geospatial, wildcard, plus partial, sparse, TTL, unique and hidden options.
  3. 37 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.
  4. 38 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.
  5. 39 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.
  6. 40 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

  1. 41 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.
  2. 42 Schema Design Patterns Learn eight MongoDB schema design patterns: subset, bucket, computed, extended reference, outlier, polymorphic, attribute and schema versioning, with runnable demos.
  3. 43 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.
  4. 44 Schema Validation Enforce document shape in MongoDB with a $jsonSchema validator, choose validationLevel and validationAction, change rules with collMod, and validate in code too.
  5. 45 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

  1. 46 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.
  2. 47 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.
  3. 48 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.
  4. 49 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

  1. 50 Replica Sets Understand MongoDB replica sets: primary and secondaries, the oplog, elections and failover, arbiters, rollbacks and replica set connection strings.
  2. 51 Sharding Learn MongoDB sharding: shards, mongos and config servers, choosing a shard key, ranged vs hashed sharding, chunks, the balancer, zones and resharding.
  3. 52 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.
  4. 53 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.
  5. 54 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

  1. 55 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.
  2. 56 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.
  3. 57 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.
  4. 58 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

  1. 59 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.
  2. 60 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.
  3. 61 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

  1. 62 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.
  2. 63 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.
  3. 64 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.
  4. 65 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.
  5. 66 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

  1. 67 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.
  2. 68 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.
  3. 69 MongoDB Interview Questions Prepare for MongoDB interviews with concise answers on concepts, indexing, schema design, aggregation, transactions, replication and sharding, plus a quiz.
  4. 70 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.