MongoDB Tutorial for Beginners
Learn MongoDB step by step, from your first document to CRUD queries, indexes, the aggregation pipeline and schema design, with real mongosh output, exercises and quizzes.
Browse all 43 lessons by stage
- Lessons
- 43
- Code examples
- 93
- Exercises
- 143
- Quiz questions
- 161
MongoDB course at a glance
Who it's for
Beginners learning their first database, JavaScript and Node.js developers building back ends, and SQL users who want to understand document databases.
Prerequisites
None for the first lessons. Familiarity with JSON and basic JavaScript helps, because queries are written in the MongoDB Shell's JavaScript syntax.
What you need
MongoDB Community Server and the MongoDB Shell (mongosh) on your computer, or a free MongoDB Atlas cluster in the cloud. MongoDB Compass is a helpful visual tool.
How long it takes
About six to eight weeks for the 25 core lessons at five hours a week, plus extra time for the in-depth guides you need.
MongoDB roadmap: beginner to advanced
Work through the 25 core chapters in the first three stages in order, then use the reference stages to go deeper. Each reference lesson links to its prerequisite and includes examples, practice and a quiz.
Beginner
Documents and collections, insert, find, query operators, projection and sorting, update, delete and data types.
- 1IntroductionLearn what MongoDB is and how it stores data as flexible JSON-like documents, how databases, collections and documents fit together, how it differs from SQL databases, and how to connect with mongosh or MongoDB Atlas.
- 2InsertAdd data to MongoDB with insertOne and insertMany, choose or generate _id values, handle duplicate key errors, understand ordered and unordered bulk inserts, and read the result each insert returns.
- 3Find & QueriesRead data from MongoDB with find and findOne, filter by exact values, combine conditions, query nested fields with dot notation, match values inside arrays, count matches, and understand cursors.
Show all 8 lessonsShow fewer
- 4Query OperatorsWrite richer MongoDB queries with operators: compare with $gt, $gte, $lt, $lte and $ne, match lists with $in and $nin, combine conditions with $and, $or and $not, check fields with $exists and $type, match patterns with $regex, and query arrays with $all, $size and $elemMatch.
- 5Projection & SortingReturn only the fields you need with projections, order results with sort, page through them with limit and skip or range-based paging, and slice arrays in the results.
- 6UpdateChange existing documents with updateOne and updateMany, use update operators such as $set, $inc, $unset, $rename, $min and $max, insert-or-update with upsert, replace whole documents, and get the updated document back with findOneAndUpdate.
- 7DeleteRemove data safely from MongoDB with deleteOne and deleteMany, return what you deleted with findOneAndDelete, drop collections and databases, expire old documents automatically with TTL indexes, and keep history with soft deletes.
- 8Data TypesChoose the right BSON type for each field: strings, 32 and 64-bit integers, doubles, Decimal128 for money, booleans, dates, ObjectIds, arrays, embedded documents and null, and check or convert types with $type and $convert.
Intermediate
Arrays, embedded documents, indexes, aggregation, $lookup, schema design, validation and text search.
- 9ArraysStore and change lists inside documents: add items with $push and $addToSet, remove them with $pull and $pop, keep arrays sorted and capped with $each, $sort and $slice, and update matching elements with the positional $ operator and arrayFilters.
- 10Embedded DocumentsModel related data in MongoDB: embed documents for data that belongs together, reference other documents by _id when data is shared or unbounded, query and update nested fields, and understand the trade-offs of duplicating data.
- 11IndexesMake queries fast with indexes: create single-field and compound indexes, follow the ESR rule for field order, enforce uniqueness, index only some documents with partial indexes, expire data with TTL indexes, and check index use with explain.
Show all 9 lessonsShow fewer
- 12Aggregation BasicsAnalyse data inside MongoDB with the aggregation pipeline: filter with $match, group and total with $group and accumulators like $sum and $avg, sort and limit results, and reshape documents with $project.
- 13Aggregation StagesGo further with aggregation: flatten arrays with $unwind, count values with $sortByCount, group numbers into ranges with $bucket, run several analyses at once with $facet, use conditional and date expressions, and save results with $out and $merge.
- 14$lookup JoinsCombine data from several collections with $lookup: match local and foreign fields, flatten single matches with $unwind or $first, filter and shape joined documents with pipeline lookups, join arrays of ids, and keep joins fast with indexes.
- 15Schema DesignDesign MongoDB schemas around how your application reads and writes data: apply the computed, subset, bucket, polymorphic, outlier and schema versioning patterns, avoid common anti-patterns, and work through a real e-commerce design.
- 16ValidationKeep data clean with schema validation: define required fields, BSON types, ranges, patterns and allowed values with $jsonSchema, add rules to existing collections with collMod, choose validation levels and actions, and read the detailed errors MongoDB returns.
- 17Text SearchAdd search to your app with MongoDB: create text indexes, search words and phrases with $text, exclude terms, sort by relevance score, weight important fields, compare with regex and collation, and know when to move to Atlas Search.
Advanced
Transactions, the Node.js driver, Mongoose, performance, replication, sharding, security, backups and monitoring.
- 18TransactionsKeep related changes consistent across several documents and collections with multi-document transactions: start a session, run operations inside withTransaction, commit or abort, handle retries, and know when single-document atomicity is enough.
- 19Node.js DriverConnect a Node.js application to MongoDB with the official driver: manage one shared MongoClient, run CRUD queries and aggregations with async/await, work with ObjectId, handle duplicate key errors, run transactions, and build an Express API on top.
- 20MongooseAdd structure to MongoDB in Node.js with Mongoose: define schemas with types, defaults and validation, create models, run queries, add virtuals, methods and middleware, link documents with populate, and know when to use lean queries or the plain driver.
Show all 8 lessonsShow fewer
- 21Performance & explainFind and fix slow MongoDB queries: read explain plans, compare keys and documents examined with results returned, spot collection scans and in-memory sorts, build covered queries, use the profiler and slow query log, and apply a repeatable tuning process.
- 22ReplicationKeep data safe and available with replica sets: understand primaries, secondaries and elections, configure a three-member set, choose write concerns for durability and read preferences for scaling reads, and handle failover in your application.
- 23ShardingScale MongoDB horizontally with sharding: understand shards, mongos routers and config servers, choose a good shard key, compare hashed and ranged sharding, avoid hot spots and scatter-gather queries, and decide when sharding is actually needed.
- 24Security & UsersLock down a MongoDB deployment: enable authentication, create users with built-in and custom roles following least privilege, restrict network access, encrypt traffic with TLS and data at rest, audit activity, and protect applications from NoSQL injection.
- 25Backup & MonitoringProtect and run MongoDB in production: back up with mongodump, snapshots and Atlas continuous backup, restore and test recovery, export data, monitor key metrics such as connections, operation latency, replication lag and disk, read serverStatus and currentOp, and set useful alerts.
Query and write references
Null and missing fields, cursor batches and cleanup, keyset pagination, bulk write ordering and errors, and versioned updates for optimistic concurrency.
- 26Null and Missing FieldsDistinguish MongoDB null from absent fields, handle array matches, use exact aggregation types, and design clear update and fallback behavior.
- 27Cursor Iteration and CleanupIterate MongoDB cursors with bounded application memory, distinguish batchSize from limit, handle partial consumption, and close owned cursors.
- 28Compound Keyset PaginationPaginate MongoDB results with compound boundaries and unique tie-breakers, matching indexes, lookahead rows, and explicit mutable-data limitations.
Show all 5 lessonsShow fewer
- 29Bulk Writes and Partial ErrorsBatch MongoDB inserts and updates with bulkWrite, compare ordered and unordered failure behavior, inspect failed indexes, and design safe reruns.
- 30Optimistic Concurrency ControlPrevent lost MongoDB document edits with version filters and atomic increments, detect stale writes, and work through a deliberate nonconflicting merge.
Data processing and storage
Window functions, dates and time zones, densify and fill, read-only views, $merge, change streams, time series, GridFS, geospatial queries and multikey indexes.
- 31Window FunctionsUse MongoDB setWindowFields for partitioned running totals, moving averages, and tied rankings while preserving rows and explicitly sorting output.
- 32Dates and Timezone BucketsGroup MongoDB dates with dateTrunc and named timezones, handle daylight-saving boundaries, and use half-open date ranges for exact daily reports.
- 33Densify and FillGenerate missing MongoDB series positions with densify, interpolate or carry values with fill, preserve observation flags, and bound generated output.
Show all 10 lessonsShow fewer
- 34Read-Only Collection ViewsCreate MongoDB read-only views from stored pipelines, observe source changes, choose underlying indexes, and distinguish views from materialized summaries.
- 35Materialized Summary RefreshRefresh MongoDB summaries with merge, unique keys, replacement and upsert rules, stale-row deletion, and a complete generation-publication exercise.
- 36Change Streams and Resume TokensWatch MongoDB replica-set changes, preserve opaque resume tokens, distinguish update lookups from event data, and transactionally deduplicate a worked event.
- 37Time Series CollectionsCreate MongoDB time-series collections, choose stable metadata and granularity, aggregate readings, and distinguish retention from exact query boundaries.
- 38GridFS File StreamingStream files through MongoDB GridFS, inspect chunks and metadata, download by stable file ID, and replace an application pointer only after upload completion.
- 39Geospatial QueriesStore longitude-first GeoJSON points, create a 2dsphere index, query nearby locations in meters, and compare proximity with polygon containment.
- 40Multikey Index LimitsUnderstand compound multikey restrictions, same-element bounds with elemMatch, and why a unique array index constrains documents rather than repeated elements.
Indexes and connection management
Collation and index matching, wildcard indexes for dynamic fields, and driver connection pools, timeouts and shutdown.
- 41Collation and Index MatchingCompare strings with explicit MongoDB collation, align query and index settings, test case-insensitive uniqueness, and apply numeric ordering to string labels.
- 42Wildcard IndexesIndex dynamic attribute paths with MongoDB wildcard indexes, scope wildcardProjection, and recognize sparse behavior and multi-predicate limits.
- 43Driver Pools and TimeoutsReuse MongoDB clients, bound per-server pools, distinguish checkout and selection timeouts, monitor pool events, and clean up controlled failures.
What is MongoDB?
MongoDB is the world's most popular document database. Instead of tables with fixed columns, it stores data as flexible, JSON-like documents with nested objects and arrays, so a product, an order or a user profile can be stored in one piece, shaped the way your application uses it. It powers apps of every size, from start-ups to global platforms, and runs on your own servers or in the cloud with MongoDB Atlas.
MongoDB pairs naturally with JavaScript and Node.js, and it scales from a laptop to clusters spread across the world. Its query language is expressive, its aggregation pipeline can analyse data inside the database, and features like replica sets, transactions and sharding make it ready for demanding production systems.
This tutorial has three stages. The beginner stage covers documents and collections, inserting, finding and filtering data, query operators, projection and sorting, updating, deleting and data types. The intermediate stage teaches arrays, embedded documents and references, indexes, aggregation pipelines, $lookup joins, schema design patterns, validation and text search. The advanced stage covers transactions, the Node.js driver, Mongoose, performance tuning, replication, sharding, security and backups.
Every lesson has examples run against a real MongoDB server with their output, common mistakes, exercises and a quiz. If you'd like to compare with relational databases, see the SQL tutorial, and to build the application around your data, the Node.js tutorial.
How to follow this course
Work through the 25 core lessons in order, because each one builds on the last. After that, the in-depth guides answer the questions production databases raise. The query and write guides cover null and missing fields, cursors, keyset pagination, bulk write errors and optimistic concurrency. The data processing and storage guides cover window functions, dates and time zones, filling gaps with $densify and $fill, read-only views, $merge, change streams, time series collections, GridFS, geospatial queries and multikey indexes. The index and connection guides cover collation, wildcard indexes and driver connection pools and timeouts. Each guide lists the core lessons to finish first.
What you will learn
10 practical skills, built one lesson at a time
- Understand documents, collections and databases, and connect with mongosh or Atlas
- Insert, find, update and delete documents with confidence
- Filter with query operators, and shape results with projection, sorting and paging
- Choose the right data types, including dates and Decimal128 for money
- Work with arrays and embedded documents, and decide when to embed or reference
- Speed up queries with indexes and check them with explain()
- Analyse data with aggregation pipelines and $lookup joins
- Design schemas with proven patterns and enforce rules with validation
- Use MongoDB from Node.js with the official driver and Mongoose, including transactions
- Run MongoDB safely with replication, sharding, security, backups and monitoring
Practise MongoDB your way
Learning sticks when you use it. Pick a mode.
MongoDB Exercises
Fill in blanks, predict output and fix broken code with instant feedback.
143 exercisesMongoDB Quiz
5, 10 or 20 questions with a timer and explanations after every answer.
161 questionsMongoDB Cheat Sheet
Every important piece of syntax on one printable page.
Open cheat sheetLearning Paths
See where MongoDB fits in a complete roadmap, and what to learn next.
View learning pathsMongoDB FAQ
Is MongoDB good for beginners?
Yes. Documents look like the JSON objects you already know from JavaScript, you can start storing data without designing tables first, and mongosh shows results immediately. The course starts from the very first document and builds up step by step.
Should I learn SQL or MongoDB first?
Both are valuable, and many applications use both. SQL databases suit highly structured, connected data and complex reporting; MongoDB suits flexible, document-shaped data and fast-changing applications. If you're building with JavaScript and Node.js, MongoDB is a natural first database. The SQL tutorial covers the relational side.
Do I need to install MongoDB?
Not necessarily. MongoDB Atlas lets you create a small cluster in the cloud and connect with mongosh or Compass in minutes. You can also run MongoDB locally with the Community Server or a single Docker command.
Is MongoDB fast enough for large applications?
Yes, when it's used well. Good schema design, the right indexes and efficient queries let a single replica set handle large workloads, and sharding spreads data across many servers when one isn't enough. The performance lessons show how to find and fix slow queries.
How long does it take to learn MongoDB?
With about an hour a day, most learners finish the beginner stage in one to two weeks and the whole course in six to eight weeks. Building a small app with Node.js and MongoDB alongside the lessons is the fastest way to make it stick.
Is this MongoDB course free?
Yes. All 25 core lessons, the 18 in-depth guides, the exercises, the quiz and the cheat sheet are free, with no account or sign-up needed.
Which MongoDB version does the course use?
The examples run on MongoDB 7 with the MongoDB Shell (mongosh). Almost everything also works on MongoDB 6 and 8; lessons point out features that need a recent server, such as $densify and $fill.
Does MongoDB support joins and transactions?
Yes. The $lookup aggregation stage joins documents from another collection, and multi-document ACID transactions work on replica sets and sharded clusters. Good schema design still keeps data that's read together in one document, so you need joins less often than in SQL.
Is MongoDB a good choice for every project?
No database is. MongoDB suits data with a flexible or nested shape, fast-changing products and high write volumes. Highly relational data with many cross-table reports can be a better fit for a SQL database, and the schema design lessons help you decide.
More tutorials
SQL
The language for asking databases questions and keeping data organised.
Start SQLGit
Track every change to your code and never lose work again.
Start GitGitHub
Host your code online, collaborate with others and publish websites.
Start GitHubHTML
The skeleton of every web page. Start here.
Start HTMLCSS
Colours, fonts, spacing and layouts that make pages beautiful.
Start CSSJavaScript
The programming language that makes web pages interactive.
Start JavaScript