100 companion flashcards · AI-assisted study content · Open the deck →
This deck is a practical introduction to MongoDB, one of the most widely used NoSQL databases. The cards walk you through the core concepts step by step, starting with the basics like the document model, BSON, and ObjectIds, before moving into the hands-on skills you'll actually use day to day, such as inserting, querying, updating, and deleting documents. You'll also get familiar with query operators and the aggregation pipeline, including key stages like $match, $group, $project, $lookup, and $unwind.
It's a great fit for developers who are new to MongoDB or switching over from a relational background, as well as students preparing for interviews or certifications that touch on NoSQL topics. If you already know SQL and want to understand how a document-oriented database thinks about data differently, this deck gives you a focused way to build that mental model without getting lost in dense documentation.
To get the most out of these cards, try to connect each concept to a real example as you study. For instance, when you review a stage like $lookup, think about how you'd join two collections in a project of your own. Because the deck mixes theory and commands, spacing your review over several short sessions will help the syntax stick better than one long cramming session, and revisiting the CRUD cards alongside the aggregation cards will reinforce how the pieces fit together.
MongoDB is a NoSQL document-oriented database designed for scalability and high performance. Unlike traditional relational databases that organize data into rigid tables, MongoDB stores information in flexible, JSON-like documents. This design makes it especially well-suited for applications with rapidly evolving schemas and large volumes of unstructured or semi-structured data, where the rigidity of relational tables would be a hindrance.
The document model is the cornerstone of MongoDB's approach to data storage. Each document is a rich data structure that resembles a JSON object, capable of containing nested fields, arrays, and sub-documents. This means related data can be stored together in a single document rather than being spread across multiple tables joined by foreign keys, which often simplifies data access patterns and reduces the need for complex joins.
Behind the scenes, MongoDB uses BSON, or Binary JSON, as its binary-encoded serialization format for both storing documents and making remote procedure calls. BSON extends JSON with additional native data types such as Date, ObjectId, int, long, double, and binary, enabling more efficient storage and traversal. Every document automatically receives a unique identifier called an ObjectId as its _id field. An ObjectId is a 12-byte value composed of a 4-byte timestamp, a 5-byte random value, and a 3-byte incrementing counter. Because of the timestamp component, ObjectIds are naturally sortable by creation time, which can be useful for ordering and indexing purposes.
MongoDB provides a comprehensive set of CRUD, or Create, Read, Update, Delete, operations that map cleanly onto everyday application needs. To create documents, you use db.collection.insertOne() for a single record or db.collection.insertMany() for multiple records. MongoDB automatically assigns an _id to each document if one is not supplied, freeing developers from manually managing unique identifiers.
Reading data is handled through db.collection.find(), which accepts a filter and an optional projection. For example, db.users.find({ age: { $gt: 25 } }) returns all users older than 25, while findOne() returns only the first matching document. To refine queries, MongoDB offers a rich set of operators. Comparison operators like $eq, $ne, $gt, $gte, $lt, $lte, $in, and $nin filter by value relationships, while logical operators such as $and, $or, $not, and $nor combine conditions. Element operators like $exists and $type check for the presence or type of fields, and array operators including $all, $elemMatch, and $size target array contents.
Updating documents is accomplished with updateOne(), updateMany(), or replaceOne(). These accept update operators that precisely describe how to modify fields: $set assigns a new value and creates the field if it does not exist, $unset removes a field, $inc increments a numeric value, $push appends to an array, and $pull removes elements from an array. The $set operator can also target nested fields using dot notation, such as "address.city". To prevent duplicates when adding to arrays, $addToSet inserts a value only if it does not already exist in the array, and combining it with $each allows multiple unique values to be added at once. Deleting documents follows the same pattern with deleteOne() and deleteMany().
The aggregation pipeline is MongoDB's primary tool for complex data analysis and transformation. It processes documents through a sequence of stages, each transforming the data and passing the result to the next stage. This approach allows developers to build sophisticated queries that would otherwise require multiple round trips or complex application-side processing.
Several stages form the foundation of most pipelines. The $match stage filters documents based on specified conditions, behaving much like a find() query; placing it early in the pipeline reduces the number of documents that subsequent stages must process. The $group stage groups documents by a specified _id expression and applies accumulators such as $sum, $avg, $min, $max, $push, and $first to compute aggregate values. The $project stage reshapes documents by including, excluding, or computing new fields, using 1 to include, 0 to exclude, or an expression to derive a value. For example, $concat can combine multiple fields into a single computed string.
When joining related data, the $lookup stage performs a left outer join with another collection, similar to a SQL JOIN. It requires specifying the target collection (from), the local field, the foreign field, and an output array field (as) that contains the matched documents. The $unwind stage, meanwhile, deconstructs an array field, producing a separate document for each element. This is invaluable when array data needs to be processed or aggregated individually. Setting preserveNullAndEmptyArrays: true ensures that documents with missing or empty arrays are not lost during the unwind operation.
Indexing is the principal mechanism for improving query performance in MongoDB. Without indexes, MongoDB performs a collection scan, examining every document in a collection to satisfy a query. By creating efficient B-tree data structures on specific fields, indexes allow MongoDB to locate matching documents directly. However, indexes consume additional storage and memory, and they slow down write operations, so they should be created strategically based on actual query patterns.
Several index types address different use cases. A single field index is created on one field, such as db.users.createIndex({ email: 1 }), where 1 indicates ascending order and -1 indicates descending. MongoDB automatically creates a single field index on the _id field. Compound indexes include multiple fields in a single index, and the order of fields matters: they support queries that match a prefix of the indexed fields, following the ESR rule (Equality, Sort, Range) for optimal field ordering. Multikey indexes are automatically created when indexing a field that holds an array, producing separate index entries for each array element, though a compound index cannot include more than one array field.
Specialized indexes serve more targeted needs. Text indexes support full-text search on string content and are queried with the $text and $search operators; each collection can have at most one text index, but it can span multiple fields. TTL, or Time-To-Live, indexes automatically remove documents after a specified number of seconds, making them ideal for session data, logs, and temporary records. Wildcard indexes, introduced in version 4.2, index all fields or all subfields of a field, which is particularly useful for polymorphic schemas with dynamic or unknown field names. To evaluate performance, the explain() method reveals whether an index was used (an IXSCAN is preferable to a COLLSCAN), how many documents were examined, and execution time. When both the query filter and projection include only indexed fields, the result is a covered query that can be satisfied entirely from the index without reading any documents, achieving totalDocsExamined: 0.
A replica set is MongoDB's primary mechanism for high availability and data redundancy. It consists of a group of MongoDB instances that maintain the same data set, including one primary node that handles all write operations and one or more secondary nodes that replicate data from the primary. If the primary fails, the replica set automatically triggers an election to promote a secondary to primary, ensuring continuous service with minimal downtime.
Replication itself works through the oplog, a special capped collection on the primary that records every write operation. Secondary nodes continuously tail the oplog and apply the operations locally, keeping their copies of the data in sync. This architecture provides data redundancy, enables automatic failover, and allows read operations to be distributed across secondaries to reduce load on the primary. When a replica set has an even number of data-bearing members, an arbiter can be added to break ties during primary elections. Arbiters participate in elections but do not hold any data, making them lightweight and resource-efficient, though they should be used sparingly in production environments.
Two important settings govern how clients interact with replica sets. Write concern specifies the level of acknowledgment requested for write operations: w: 0 means no acknowledgment, w: 1 means acknowledgment from the primary alone (the default), and w: "majority" requires acknowledgment from a majority of members. Higher write concern improves durability at the cost of latency. Read preference, on the other hand, determines which members receive read operations. Options include primary (the default), primaryPreferred, secondary, secondaryPreferred, and nearest (the member with the lowest latency). Together, these settings allow applications to balance consistency, availability, and performance based on their specific requirements.
Sharding is MongoDB's strategy for horizontal scaling, enabling databases to handle data sets and throughput levels that exceed the capacity of any single server. In a sharded deployment, data is distributed across multiple machines called shards, with each shard holding only a subset of the total data. The basis for this distribution is a shard key, an indexed field or compound of fields that MongoDB uses to determine where each document belongs.
A sharded cluster consists of three main components. Shards store the actual data, and each shard is itself a replica set, providing both scalability and redundancy. Config servers store metadata and configuration information for the entire cluster, including the mapping of shard key ranges to shards. Mongos instances act as query routers, receiving client operations and directing them to the appropriate shards based on the shard key. Clients typically connect to one or more mongos processes rather than directly to shards, which insulates applications from the underlying distribution of data.
Choosing a good shard key is one of the most consequential decisions in sharded cluster design. An effective shard key should have high cardinality, low frequency so that no single value dominates, and should distribute writes evenly across shards. A poor shard key leads to hot spots, where one shard receives disproportionately more traffic and becomes a bottleneck. Once chosen, the shard key is difficult to change, so careful planning and testing are essential before deployment.
MongoDB's flexible document model enables several schema design patterns that differ from traditional relational approaches. The two fundamental strategies are embedding and referencing. Embedded documents store related data within a single document, which is denormalized and ideal for one-to-few relationships where data is always accessed together. Referenced documents, by contrast, store relationships using ObjectId references in a normalized manner, which works better for one-to-many or many-to-many relationships and for data that is accessed independently. Embedding provides faster reads by avoiding joins, while referencing offers smaller document sizes and easier updates of shared data.
Several guidelines help decide when to use each approach. Embedding is preferable when data is always accessed together, when the relationship is one-to-few, and when data does not change frequently. Referencing is preferable when data is accessed independently, when relationships are one-to-many or many-to-many, when documents might otherwise exceed MongoDB's 16 megabyte BSON document size limit, and when data is updated frequently. For files larger than 16MB, GridFS provides a specification for splitting files into 255KB chunks stored across two collections: fs.files for metadata and fs.chunks for binary data.
Beyond embedding and referencing, several advanced patterns address specialized needs. Capped collections are fixed-size collections that automatically overwrite the oldest documents when full, maintaining insertion order and supporting high-throughput operations; they are ideal for logs and caches. The bucket pattern groups related data, such as time-series measurements, into fixed-size buckets within a single document, reducing document count and improving read performance. The polymorphic pattern stores documents of different shapes in the same collection, distinguished by a discriminator field like type, leveraging MongoDB's flexible schema for varied entity types. Finally, the attribute pattern restructures documents with many similar fields into an array of key-value pairs, enabling efficient indexing and querying across any attribute.
MongoDB provides a rich ecosystem of features and tools beyond basic CRUD operations. Multi-document ACID transactions, supported since version 4.0 for replica sets and 4.2 for sharded clusters, ensure atomicity across multiple operations and collections. Transactions are managed through a session that calls startTransaction(), performs the operations, and then either commitTransaction() or abortTransaction(). Change streams offer a subscription-based API for real-time data changes, returning a cursor via db.collection.watch() that emits events for inserts, updates, deletes, and replacements, enabling event-driven architectures without polling the oplog.
For deployment and management, MongoDB Atlas is the fully managed cloud database service, available on AWS, Azure, and Google Cloud. It provides automated provisioning, scaling, backup, monitoring, and security features, including a free M0 tier for development. Atlas Search adds Apache Lucene-powered full-text search capabilities that go beyond basic text indexes. For local interaction, mongosh is the modern command-line shell replacing the legacy mongo shell, with syntax highlighting, intelligent autocomplete, and built-in help. MongoDB Compass provides an official graphical interface for exploring data, building queries visually, viewing query plans, managing indexes, and constructing aggregation pipelines stage by stage.
Compared to SQL databases, MongoDB differs in several key ways. Its document-based data model replaces tables with collections and rows with documents, and its schema-flexible approach eliminates the need for predefined table structures. Joins in MongoDB are performed through the $lookup aggregation stage or by embedding related data, rather than the SQL JOIN syntax. Scaling is fundamentally horizontal through sharding rather than the vertical scaling typical of relational systems. Both support ACID transactions, though SQL databases have more mature transaction implementations. For full-text search within a self-hosted MongoDB, text indexes support queries using the $text operator with $search, and results can be sorted by relevance using $meta: "textScore".
$match stage filters documents based on specified conditions, similar to a find() query. It should be placed early in the pipeline to reduce the number of documents processed by subsequent stages. Example: { $match: { status: "active" } }.Date value: db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 }). TTL indexes are useful for session data, logs, and temporary records.$sample stage randomly selects a specified number of documents from the pipeline. Example: { $sample: { size: 10 } } returns 10 random documents. Internally, it uses a pseudo-random cursor and is used for statistical sampling.w: 'majority' confirms that a write has been applied to a majority of replica set members (including the primary). It provides strong durability guarantees but adds latency. The wtimeout option sets a time limit; if not met, the write returns an error.validationAction option controls what happens when a document fails schema validation. error (default) rejects the write. warn allows the write but logs a warning. Set it when creating or modifying a collection's validator.db.users.createIndex({ email: 1 }, { partialFilterExpression: { active: true } }). It saves storage and write overhead for collections where only a subset of documents need indexing.Drill this topic
100 flashcards on Nosql MongoDB — free, no signup needed to start.
Study Nosql MongoDB flashcardsLearnWiki pages are generated with AI assistance from LearnCoachAssist's reviewed study catalog and may contain errors — verify anything critical against your course materials.