MongoDB · Free Practice Questions · Last reviewed May 2026
36real exam-style questions organised by domain, each with the correct answer highlighted and a plain-English explanation of why it's right — and why the others are wrong.
An e-commerce application stores products in a collection. Each product has a variable number of attributes, such as 'size', 'color', or 'material'. Which data modeling approach best leverages MongoDB's flexible schema while maintaining query efficiency?
Normalize all attributes into a secondary 'attributes' collection linked by ProductID.
Implement a fixed schema using a single large object containing every possible attribute as a null value.
Embed variable attributes directly within each product document.
Embedding directly supports data locality, allowing the entire product state to be fetched in a single read operation. Since MongoDB documents are schemaless, having varying fields across products is natively supported, efficient for indexing, and avoids the performance degradation associated with relational JOINs in highly dynamic datasets.
Serialize the entire attribute set into a single base64-encoded string field.
Which of the following describes the behavior of the BSON format within MongoDB?
It is a text-based format identical to JSON but with limited character support.
It supports a subset of data types compared to standard JSON.
It is a binary-encoded serialization of JSON documents.
BSON provides a binary representation that allows for rapid traversal and encoding. By using length prefixes, it enables the database to skip over fields or documents without parsing the entire structure, which is a major performance boost for complex read operations compared to standard JSON text parsing.
It requires manual conversion by the driver for every read operation.
Refer to the exhibit. Why would an operation attempting to insert the document shown in the exhibit fail?
The '_id' field is invalid.
The field 'metadata' is a reserved keyword.
The field '$created' starts with a reserved character.
MongoDB reserves the dollar sign ($) at the beginning of a field name for its own internal operators, such as $set or $push. Because the database tries to evaluate '$created' as an operator instead of a string key, the document insertion will be rejected by the server as invalid.
The value 'null' is not allowed for the 'last_login' field.
Which document design pattern should be used to store a one-to-many relationship where the child documents are frequently accessed together with the parent?
Normalize the data by creating a separate collection for child documents.
Embed child documents directly as an array within the parent document.
Embedding captures the relationship within a single atomic unit. By storing children in an array, you allow the database to return the entire hierarchical data structure in a single operation. This improves performance and simplifies application logic because the database handles the retrieval of the entire record structure.
Store the child data in a separate database to isolate the write load.
Use a flat structure and duplicate parent information in every child document.
Which of the following describes the 'schema-flexible' nature of MongoDB?
All documents must have a predefined structure determined by the first document inserted.
Documents can have different fields, and the structure can change over time.
MongoDB allows documents in the same collection to vary in structure and field types. This adaptability is critical for applications that need to evolve their data models rapidly. Developers can add new features without disruptive migration processes, allowing for continuous delivery and seamless updates to the application's underlying data.
The database automatically flattens all nested documents upon insertion.
Schema enforcement can only be achieved by using third-party database proxies.
What is the primary benefit of the 'Bucket Pattern' in MongoDB data modeling?
It eliminates the need for any indexing on the collection.
It keeps document sizes within reasonable limits for time-series data.
By grouping related events into a single document based on a time interval, the Bucket Pattern prevents the growth of documents that could otherwise exceed the 16MB limit. This design improves memory management and performance by allowing the database to read and write fewer, more relevant documents.
It forces data normalization across multiple sharded clusters.
It automatically migrates old data to archival storage systems.
Want more MongoDB Overview and Document Model practice?
Practice this domainRefer to the exhibit. What is the impact of setting 'dynamic' to true in this Atlas Search index definition?
It forces all documents to follow a strict schema.
It prevents the creation of any custom field mappings.
It automatically indexes all fields in every document.
When dynamic mapping is enabled, Atlas Search scans the documents and automatically indexes every field it encounters. This provides a 'search-everything' capability out of the box, which is extremely convenient for collections where you do not want to manually define mappings for every individual document field.
It disables the indexing of nested object fields.
When using MongoDB Compass to analyze query performance, which tool is most effectively used to view the explain plan output in a visual format?
The Aggregation Pipeline builder.
The Explain Plan tab.
The Explain Plan tab in Compass displays the execution metrics in a clear, visual format. It provides details on stage transitions, index scans, and document counts, making it the primary tool within the GUI for interpreting how the database engine processes queries and where performance issues arise.
The Schema validation tab.
The Connection health monitor.
Which of the following describes the behavior of a 'write concern' in a MongoDB transaction?
Write concern is ignored inside multi-document transactions.
It is applied to each individual operation within the transaction.
It is specified during the commitTransaction command.
The write concern is explicitly set when calling commitTransaction. This allows the application to control the acknowledgement level for the entire transaction block. This mechanism is standard for ensuring that all changes are successfully hardened on the required number of nodes before the application considers the transaction finished.
It is determined solely by the server's default configuration.
Refer to the exhibit. What is the most appropriate next step for an application encountering this error?
Display an error message to the user and stop.
Retry the individual failed operation only.
Abort the transaction and retry the entire operation.
When a TransientTransactionError occurs, the correct procedure is to abort the failed transaction and execute the entire sequence of operations again. This guarantees that all changes are applied atomically, adhering to the ACID properties of the transaction and ensuring that the final state is correct and consistent.
Ignore the error and continue with the next request.
When using the MongoDB C#/.NET driver, which object is essential for managing the scope and lifecycle of a multi-document transaction?
IMongoDatabase
IClientSessionHandle
IClientSessionHandle is the standard interface in the C# driver for managing sessions and transactions. It allows developers to start, commit, and abort transactions safely. By passing this object into every operation, you link them to the same session, enabling the ACID properties required for multi-document operations.
MongoClient
IMongoCollection
Which of the following best describes the purpose of the MongoDB 'mongosh' shell?
To act as a GUI for database administration.
To serve as a modern interactive JavaScript shell.
mongosh is a full-featured JavaScript environment that allows developers to run commands against MongoDB. It is designed to be the primary interactive shell for developers, providing enhanced usability, better autocompletion, and support for the latest MongoDB features, significantly improving the experience over the previous, deprecated 'mongo' shell.
To perform background replication between nodes.
To automatically optimize database query indexes.
Want more Drivers, Tools, Transactions, and Search practice?
Practice this domainWhich stage should be placed first in an aggregation pipeline to optimize performance when filtering a large collection based on an indexed field?
$project
$match
The $match stage serves as a query filter that can utilize existing indexes when placed at the beginning of a pipeline. By reducing the number of documents passed to downstream stages, it saves CPU and memory. This is the standard practice for performance optimization in MongoDB aggregation pipelines.
$group
$sort
Which TWO stages are considered 'blocking' stages that can potentially consume excessive memory if not managed correctly?
$match
$group
The $group stage must consume all input documents to calculate aggregate results like sums or averages. Because it must see the entire stream to finalize values for grouping keys, it is a blocking operation that requires significant RAM. Developers must be cautious with memory limits when grouping.
$sort
The $sort stage is blocking because it needs the full set of documents to determine their relative order. While it can use indexes to avoid memory issues, a sort without an index must pull all documents into memory, potentially exceeding the 100MB limit during the sorting process.
$project
$limit
Which operator is used within a $project stage to calculate the square root of a numerical field?
$pow
$sqrt
The $sqrt operator is the standard aggregation function for calculating the square root of a non-negative number. It is highly optimized for performance and is the correct choice for mathematical transformations involving square roots within an aggregation pipeline's $project or $addFields stages.
$abs
$exp
In an aggregation pipeline, what is the purpose of the $addFields stage?
It removes all existing fields and replaces them with new ones.
It adds new fields to documents, preserving existing fields.
$addFields adds specified fields to the input documents, and if a field already exists, it updates its value with the result of the expression. This is the standard mechanism for augmenting documents without losing pre-existing data, providing maximum flexibility for data reporting and transformation tasks.
It filters the collection based on newly added fields.
It is a deprecated stage replaced by $project.
What happens if an aggregation stage exceeds the 100MB memory limit and 'allowDiskUse' is set to false?
The pipeline execution stalls until memory is freed.
The database automatically increases the limit.
The aggregation operation fails and returns an error.
When memory usage exceeds 100MB and allowDiskUse is false, the database throws an error to prevent resource exhaustion. This forces developers to design more efficient pipelines or intentionally enable disk usage, ensuring that resource-heavy queries are executed with full awareness of the potential performance trade-offs.
The pipeline skips the stage and continues.
Which operator is used to calculate the average value of a numeric field in a $group stage?
$mean
$sum
$avg
$avg is the standard accumulator used to calculate the arithmetic mean. It automatically handles the summation and division by the count of documents, providing a clean and efficient way to summarize numeric trends within the aggregation pipeline's grouping phase.
$median
Want more Aggregation Framework practice?
Practice this domainYou have a collection of user activity logs where queries frequently filter by `userId` and sort by `timestamp` in descending order. Which single index definition provides optimal support for this query pattern without requiring an in-memory sort?
{ userId: 1, timestamp: 1 }
{ timestamp: -1, userId: 1 }
{ userId: 1, timestamp: -1 }
A compound index on userId ascending then timestamp descending matches both the equality filter and the sort order, so MongoDB walks the index in the required descending sequence and returns results without an in-memory sort stage, satisfying the no-blocking-sort constraint.
{ userId: -1, timestamp: -1 }
An e-commerce application frequently executes a query filtering by 'category' and 'brand', and then sorts the results by 'price' in ascending order. You created a compound index on { category: 1, brand: 1, price: 1 }. Which statement best describes how MongoDB utilizes this index for a query that filters only on 'brand' and 'price'?
The query engine will perform an index scan because 'brand' and 'price' are part of the index.
MongoDB will perform a collection scan as the query lacks the 'category' prefix required by the index.
The index prefix rule dictates that a query must use the first field of the compound index to enable an index scan. Because 'category' is omitted, the query engine cannot utilize the B-tree structure of the index for 'brand' and 'price', resulting in a full collection scan to find matching documents.
The index will be used only for the sort operation on 'price' but not for the filter on 'brand'.
MongoDB will use the index to find 'brand' but will still need to fetch documents to verify 'price'.
You are designing a schema for a social media platform where users have an array of 'tags' and an array of 'mentions'. You attempt to create an index on { tags: 1, mentions: 1 }. What is the most likely outcome of this operation?
The index is created successfully and supports queries that filter by both tags and mentions.
The index build fails with an error stating that a compound index cannot include more than one array.
A compound index can only contain one field that is an array to maintain a manageable index size. If you try to index two different array fields in one compound index, MongoDB returns an error to prevent the explosive growth of index entries that would occur from mapping every possible combination of elements.
The index is created but only the first element of each array is indexed to save space.
The index is created but it will only be used if the query provides a specific index hint.
Your application executes the query: db.users.find({ age: { $gt: 30 } }, { age: 1, _id: 0 }). You have an index on { age: 1 }. How does MongoDB process this query?
MongoDB performs an index scan followed by a fetch to get the 'age' values.
This is a covered query, and MongoDB retrieves all data from the index alone.
The query is considered 'covered' because the index on { age: 1 } contains the 'age' field used in the filter, and the projection only asks for 'age' while excluding '_id'. By satisfying the query without accessing the actual documents, MongoDB reduces disk I/O and speeds up the response time significantly.
MongoDB must fetch the documents because projections are not supported in covered queries.
The query cannot be covered because the _id field is always required from the document.
You are considering using a hashed index for a 'product_id' field to distribute data across shards. Which of the following is a known limitation of hashed indexes in MongoDB?
Hashed indexes do not support equality matches, only range queries.
Hashed indexes can only be created on fields that contain unique values.
Hashed indexes do not support range-based queries or sort operations.
Because hashing transforms values into a pseudo-random distribution, the original order of the data is lost. A query for values greater than 100 cannot use a hashed index because the hash of 101 might be numerically smaller or larger than the hash of 1000, making the B-tree structure useless for ranges.
Hashed indexes are only available in the MongoDB Enterprise Edition.
Refer to the exhibit. If a query is executed as db.collection.find({ "metadata.type": "book" }), how will MongoDB use the created index?
The index will be used to quickly find all documents where 'type' is 'book'.
MongoDB will perform a collection scan because the index is on the whole object.
By indexing 'metadata', you are indexing the full BSON subdocument. Queries on sub-fields like 'metadata.type' are not supported by this index. For the index to be useful for the given query, it should have been created on the specific path 'metadata.type' using dot notation in the createIndex command.
The index will be used, but performance will be slower than a dot-notation index.
The index build will fail because metadata is a nested document.
Want more Indexing practice?
Practice this domainAn application needs to update a user document in the 'users' collection. If the document does not exist, a new document must be inserted using fields from both the filter and the update document. Which parameter accomplishes this behavior in MongoDB?
Setting the { writeConcern: { w: 'majority' } } option during the update operation.
Setting the { returnDocument: 'after' } option in the findOneAndUpdate method.
Setting the { upsert: true } option in updateOne or findOneAndUpdate.
Upsert combines update and insert semantics in one atomic operation: when no document matches the filter, MongoDB inserts a new document built from the filter equality fields plus the update operators. This exactly meets the requirement to insert using fields from both documents.
Setting the { multi: true } option to force updates across multiple matching records.
You are designing an e-commerce catalog where products can have a dynamic array of tags. You need to query for documents where the 'tags' array contains both 'electronics' and 'sale' simultaneously, regardless of their order or other elements. Which query operator should you use?
{ tags: { $in: ['electronics', 'sale'] } }
{ tags: { $all: ['electronics', 'sale'] } }
$all matches documents whose tags array contains every listed element, independent of order, duplicates or extra values. That precisely satisfies the requirement for simultaneous presence of both 'electronics' and 'sale', which a simple equality match cannot guarantee.
{ tags: ['$electronics', '$sale'] }
{ tags: { $elemMatch: { $eq: 'electronics', $eq: 'sale' } } }
A support ticketing system stores documents in the 'tickets' collection. An operator wants to add a new field 'priority' set to 'high' only for tickets whose 'status' is 'open' and that do not already have a 'priority' field. The update must not create any new documents and must not modify tickets that already have a 'priority' field. Which update operation should be used?
db.tickets.updateMany({ status: 'open' }, { $set: { priority: 'high' } }, { upsert: true })
db.tickets.replaceOne({ status: 'open', priority: { $exists: false } }, { status: 'open', priority: 'high' })
db.tickets.updateMany({ status: 'open', priority: { $exists: false } }, { $set: { priority: 'high' } })
This operation uses updateMany with a filter that matches only open tickets lacking a priority field, and $set adds the field without inserting new documents. Because the filter includes $exists: false, tickets that already have priority are untouched, and updateMany never performs an upsert unless explicitly requested, so no new documents are created.
db.tickets.updateMany({ status: 'open', priority: { $exists: false } }, { $setOnInsert: { priority: 'high' } })
A logistics application stores shipment documents in the 'shipments' collection. Each document has a 'packages' array of embedded subdocuments, each with a 'trackingCode' field. A developer needs to remove only the embedded subdocument whose 'trackingCode' equals 'TRK-9981' from the document with '_id' 42, leaving all other packages untouched. Which update operation should be used?
db.shipments.updateOne({ _id: 42 }, { $pull: { packages: { trackingCode: "TRK-9981" } } })
The $pull operator removes every array element that matches the supplied condition, so this deletes only the embedded package whose trackingCode equals TRK-9981 while preserving the rest of the array and the parent document. The filter on _id restricts the update to the intended shipment, making this the precise and minimal operation for the scenario.
db.shipments.updateOne({ _id: 42 }, { $pullAll: { packages: ["TRK-9981"] } })
db.shipments.updateOne({ _id: 42, "packages.trackingCode": "TRK-9981" }, { $unset: { "packages.$": "" } })
db.shipments.updateOne({ _id: 42 }, { $pop: { packages: 1 } })
A reporting service reads from the 'sensors' collection, which holds millions of documents each containing an 'active' boolean field. The service queries only for documents where 'active' is true and reads a handful of fields. A developer wants the query to avoid scanning documents that are inactive. Which index should be created to support this access pattern most directly?
db.sensors.createIndex({ active: 1 }, { sparse: true })
db.sensors.createIndex({ _id: 1, active: 1 })
db.sensors.createIndex({ active: 1 })
A single-field ascending index on 'active' lets the query planner satisfy the equality predicate on that field by scanning only the matching index entries and fetching the corresponding documents. Because the filter is a simple equality on one field, this index directly narrows the candidate set and avoids a full collection scan for the inactive documents.
db.sensors.createIndex({ active: "text" })
A logistics application stores shipment records in the 'shipments' collection. Each document includes a 'status' field and a 'deliveredAt' field (a Date). A developer must set 'deliveredAt' to the current date and time for every shipment whose 'status' is 'in_transit' and whose 'carrier' is 'FastShip'. Which operation satisfies this requirement with a single command?
db.shipments.updateOne({ status: 'in_transit', carrier: 'FastShip' }, { $set: { deliveredAt: new Date() } })
db.shipments.updateMany({ status: 'in_transit', carrier: 'FastShip' }, { $set: { deliveredAt: new Date() } })
updateMany applies the $set update operator to every document matching the filter { status: 'in_transit', carrier: 'FastShip' }, writing the current date into deliveredAt. The filter combines both conditions with implicit AND, which matches the requirement exactly and updates all qualifying shipments in one round trip.
db.shipments.replaceMany({ status: 'in_transit', carrier: 'FastShip' }, { deliveredAt: new Date() })
db.shipments.findAndModify({ query: { status: 'in_transit', carrier: 'FastShip' }, update: { $set: { deliveredAt: new Date() } }, multi: true })
Want more CRUD Operations practice?
Practice this domainAn e-commerce application stores products with fluctuating attributes. Which data modeling pattern is most effective for handling diverse product schemas while maintaining efficient filtering?
Embedding every possible attribute as a top-level field in the document.
Storing all product attributes as a single large JSON blob string.
Implementing the Attribute Pattern with an array of key-value pairs.
This pattern creates a standardized structure that allows you to index the key and value fields uniformly. It enables efficient queries across different product types without modifying the schema, ensuring that MongoDB can perform high-performance index lookups regardless of which specific attributes are stored for a given document.
Creating a separate collection for every individual product category.
Refer to the exhibit. You are implementing the Subset Pattern for a user profile that tracks recent orders. As the number of orders per user grows indefinitely, which strategy prevents the 'unbounded array' anti-pattern?
Move all orders to a separate collection and reference them by ID in the user document.
Keep only the 10 most recent orders in the array and offload older orders to a separate collection.
This is the core implementation of the Subset Pattern. By limiting the array size to a manageable count, you guarantee the user document stays small and performant. Historical data remains accessible via a secondary query only when requested, optimizing for the common case of viewing recent activity.
Increase the maximum document size limit to accommodate the growing order array.
Use a capped collection for the orders array to automatically drop old orders.
Which TWO of the following scenarios are optimal for using the Embedding pattern instead of Referencing?
A blog post containing a list of comments that grows indefinitely.
A user document containing the user's primary shipping address.
Addresses have a strong 'contains' relationship with the user and are rarely queried independently of the user profile. Embedding them allows the application to retrieve both the user identity and their shipping information in a single read operation, significantly reducing application-side latency and database server load.
A product catalog with millions of items linked to various categories.
A movie document embedding the names of its three main cast members.
The number of main cast members is small and relatively static, fitting the one-to-few pattern perfectly. Embedding them allows the application to display core movie details immediately without needing secondary lookups, providing a much faster user experience for common read operations on the movie details page.
A sensor data stream that stores millions of readings per hour.
Refer to the exhibit. You have a collection where each document contains a 'tags' array. If you frequently query for documents containing specific tags, what is the best way to model and index this data?
Convert the tags array into a comma-separated string.
Use the multikey index created on the tags array.
Multikey indexes are the native way MongoDB handles array indexing. When an index is created on a field that contains an array, MongoDB automatically creates entries for each element, allowing for high-speed retrieval of documents based on specific tag values without any additional configuration or complex data restructuring.
Create one index per tag value to ensure performance.
Store tags in a separate collection and reference them using an object ID.
You are designing a schema for a social media platform. A user has a 'profile' document, and they can have thousands of 'followers'. How should you model the follower relationship?
Embed all follower IDs in an array within the user profile document.
Create a separate collection for followers and store references.
Storing followers in their own collection allows the system to scale to millions of followers per user. You can index the user ID field in this collection to perform fast lookups, ensuring that the user document remains small and that follow counts can be efficiently managed via aggregation queries.
Use the Attribute Pattern to store each follower as a key-value pair.
Store the followers in a gridFS file to handle the large size.
When designing a schema for a time-series dataset, why is it recommended to use the 'Bucket' pattern?
It allows for unlimited document growth without checking the 16MB limit.
It reduces index size and improves read performance by grouping data.
The Bucket pattern aggregates multiple individual readings into a single document. This creates a much smaller index, as there is one entry per bucket rather than one entry per individual reading. This allows the working set to fit better in memory, dramatically increasing the speed of time-based query operations.
It automatically converts all data to a binary format for faster storage.
It enables ACID transactions for non-related collections automatically.
Want more Data Modeling practice?
Practice this domainThe C100DEV exam has 60–90 questions and must be completed in 120 minutes. The passing score is 700/1000.
Scenario-based questions covering exam objectives with detailed answer explanations.
The exam covers 6 domains: MongoDB Overview and Document Model, Drivers, Tools, Transactions, and Search, Aggregation Framework, Indexing, CRUD Operations, Data Modeling. Questions are weighted by domain — higher-weight domains appear more on your actual exam.
No. These are original exam-style practice questions written against the official MongoDB C100DEV exam objectives. They are not copied from the real exam. Courseiva focuses on genuine understanding, not memorisation of braindumps.
Courseiva tracks your accuracy per domain and routes you toward weak areas automatically. Free, no account required.