Courseiva

CCNA Mongodb Overview Document Model Questions

38 questions · Mongodb Overview Document Model topic · All types, answers revealed

1
MCQmedium

A developer is building a MongoDB application that stores social media posts. Each post document includes an array of comments, and each comment is a subdocument with fields such as author, text, and timestamp. The developer later needs to update a specific comment's text. Which update operation should they use to modify only the targeted comment's text without replacing the entire comments array?

A.db.posts.updateOne({ _id: postId }, { $set: { comments: [{ author: "Alice", text: "updated text" }] } })
B.db.posts.updateOne({ _id: postId, "comments.author": "Alice" }, { $set: { "comments.$.text": "updated text" } })
C.db.posts.updateOne({ _id: postId }, { $set: { "comments.$.text": "updated text" } })
D.db.posts.updateOne({ _id: postId }, { $push: { comments: { author: "Alice", text: "updated text" } } })
AnswerB

The query includes a condition that matches a specific element in the comments array (comments.author: "Alice"), and the update uses the positional $ operator to set the text field of the first matching array element. This is the correct way to update a single subdocument within an array without replacing the entire array. The $ operator refers to the matched array element, ensuring only that comment is modified.

Why this answer

To update a specific subdocument within an array, MongoDB provides the positional $ operator, which acts as a placeholder for the first array element that matches the query condition. The query must include a filter on the array field to identify which element to update. This approach modifies only the targeted subdocument without affecting other elements or replacing the entire array.

Exam trap

The trap here is assuming that the positional $ operator works without a matching array condition in the query filter, which would cause an error or unintended update.

2
MCQmedium

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?

A.Normalize all attributes into a secondary 'attributes' collection linked by ProductID.
B.Implement a fixed schema using a single large object containing every possible attribute as a null value.
C.Embed variable attributes directly within each product document.
D.Serialize the entire attribute set into a single base64-encoded string field.
AnswerC

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.

Why this answer

Using a polymorphic schema with optional fields directly in the document is the canonical MongoDB approach. This strategy avoids the JOIN operations required by relational databases when attributes are stored in separate tables. By keeping data together, developers achieve high performance for read operations and take full advantage of MongoDB's indexing capabilities on specific document fields, regardless of whether every document contains that field.

Exam trap

Developers often use a separate collection for every optional attribute, erroneously trying to mimic relational EAV patterns instead of using flexible embedded fields.

3
MCQmedium

A developer is using the MongoDB Node.js driver to insert a document into a collection. The document includes a field `_id` set to a custom string value. After the insert, the developer checks the returned result and notices that the `insertedId` matches the custom string. What does this indicate about MongoDB's handling of the `_id` field?

A.MongoDB automatically generates an ObjectId for the `_id` field if it is not provided, but if provided, it must be unique within the collection.
B.The `_id` field is always an ObjectId and cannot be overridden with a custom value.
C.The `_id` field is only unique per shard, not across the entire collection.
D.MongoDB automatically indexes the `_id` field only if it is an ObjectId.
AnswerA

In MongoDB, every document must have an `_id` field that acts as a primary key. If the `_id` is not specified, the driver generates an ObjectId. If a custom value is provided, it can be any BSON type except an array, but it must be unique within the collection. The insert succeeds only if the custom `_id` does not already exist, ensuring uniqueness.

Why this answer

The `_id` field is the primary key for MongoDB documents. If omitted, the driver generates an ObjectId; if provided, it can be any BSON type except an array, but it must be unique within the collection. MongoDB automatically creates a unique index on `_id`.

The scenario confirms that a custom string was accepted and used as the `_id`, demonstrating this flexibility.

Exam trap

The trap here is thinking that `_id` must be an ObjectId, when in fact MongoDB allows any BSON type except arrays for the `_id` field.

4
MCQeasy

A developer is designing a MongoDB collection to store blog posts. Each post has a title, content, and an array of tags. The developer wants to ensure that the tags field is always an array of strings. Which BSON data type should be used for the tags field?

A.Object
B.BinData
C.String
D.Array
AnswerD

The Array BSON type is designed to store ordered lists of values, which can include strings. Using an array for tags allows multiple tags to be stored in a single field, and MongoDB supports querying and indexing array elements. This matches the requirement of an array of strings.

Why this answer

MongoDB's document model supports arrays natively, allowing a field to hold multiple values. For a tags field that should contain multiple strings, the Array BSON type is the correct choice. It enables efficient querying (e.g., finding posts with a specific tag) and indexing (multikey indexes), and it aligns with the flexible schema design that MongoDB encourages.

Exam trap

The trap here is confusing a String, which holds one value, with an Array, which holds multiple values; the requirement specifically calls for multiple tags.

5
MCQeasy

A team is designing a MongoDB collection to store user profiles. Each profile document includes a `name` string, an `age` integer, and an array of `hobbies` strings. A new developer asks which BSON type is used to represent the `hobbies` field in the stored document. What is the correct BSON type for an array of strings?

A.Binary data
B.Array
C.Object
D.String
AnswerB

In BSON, an array is a distinct type that holds an ordered list of values, and it is exactly what MongoDB uses to store fields like `hobbies` that contain multiple strings. The array type supports indexing and query operators such as `$elemMatch`, and it is the native representation for lists in documents, so this is the correct type.

Why this answer

MongoDB documents are stored in BSON, which includes an Array type for ordered lists of values. A field like `hobbies` that contains multiple strings is represented as a BSON array of strings. This allows the database to index the array elements, query with operators like `$in` or `$elemMatch`, and update individual elements, making Array the correct and natural choice.

Exam trap

The trap here is confusing the BSON type of the field with the types of its elements; the field itself is an Array even though its elements are Strings.

6
MCQmedium

A development team is building a MongoDB application to store user profiles. They want to enforce that every user document contains an 'email' field of type string, and they want documents that violate this rule to be rejected at insert time. Which MongoDB feature should they use?

A.JSON Schema validation with the $jsonSchema operator in the collection's validator option
B.Storing the email in a separate collection with a reference
C.Unique index on the 'email' field
D.Application-level validation using Mongoose schema definitions
AnswerA

MongoDB supports schema validation at the collection level using the $jsonSchema operator, which allows specifying required fields, BSON types, and other constraints. When configured, inserts and updates that do not match the schema are rejected, providing data integrity while still allowing flexible fields not covered by the schema.

Why this answer

MongoDB's JSON Schema validation allows developers to enforce a schema on a collection while still accommodating flexible fields. By defining a validator with $jsonSchema, the team can require the 'email' field and ensure it is a string. This provides server-side enforcement, ensuring that any insert or update that violates the schema is rejected, regardless of the client used.

Exam trap

The trap here is assuming that a unique index enforces field presence and type, when it only enforces uniqueness and only for documents that contain the field.

7
Multi-Selectmedium

A developer is designing a MongoDB collection to store blog posts. Each post document includes an array of comments, and each comment has fields such as 'author', 'text', and 'timestamp'. The developer wants to optimize for queries that retrieve posts along with their comments, and also wants to ensure that comments are stored efficiently. Which two of the following statements are true regarding the document model in this scenario? (Choose two.)

Select 2 answers
A.Storing comments in a separate collection and referencing them from the post document reduces data duplication.
B.Embedding comments always improves write performance because it requires only a single document update.
C.Using the $slice operator in a query can limit the number of comments returned from an embedded array.
D.Embedding comments as an array within the post document allows retrieving the post and its comments in a single query.
E.The 16MB document size limit may be a consideration if a post accumulates a very large number of comments.
AnswersD, E

Embedding comments in the post document stores all related data together, so a single query can fetch the post and all its comments. This is efficient for read operations that need the complete post with comments, and it leverages MongoDB's document model to avoid additional queries.

Why this answer

Embedding comments within the post document allows retrieving the post and comments in one query, which is efficient for read-heavy access patterns. However, the 16MB document size limit must be considered if comments grow unbounded. The other statements are either incorrect or not directly related to the document model design in this scenario.

Exam trap

The trap here is assuming that embedding is always the best choice without considering document size limits or that referencing always reduces duplication, while the question asks for true statements about the model.

8
MCQmedium

A development team is modeling a MongoDB collection for a ticketing system. Each ticket has a unique ticketId, a status, and a variable set of custom fields that differ by department. The team wants to ensure that queries on ticketId and status can use indexes efficiently and that the custom fields remain flexible. Which statement best describes how the document model supports this requirement?

A.Documents in the same collection can have different fields, and indexes on ticketId and status can be created regardless of the custom fields present.
B.MongoDB enforces a collection-level schema, so the team must define all custom fields in a validator before inserting tickets.
C.Custom fields must be stored in a separate collection because MongoDB does not allow arrays or subdocuments in the same collection as scalar fields.
D.Indexes in MongoDB are created on collections, not fields, so the team cannot index ticketId and status without also indexing all custom fields.
AnswerA

MongoDB collections are schema-flexible, so each ticket document can contain a different set of custom fields while sharing common fields such as ticketId and status. Indexes are defined on specific fields and do not require every document to contain those fields. This allows efficient queries on ticketId and status while keeping department-specific fields flexible, which is exactly what the team needs.

Why this answer

The document model allows each ticket to have its own shape while sharing common fields. Indexes are created on specific fields such as ticketId and status, and they work even when documents contain additional custom fields. This gives the team efficient lookups on the common fields and the flexibility to store department-specific data without schema migrations.

Exam trap

The trap here is thinking that a flexible schema prevents indexing or that indexes must cover every field, when in fact indexes are defined on specific fields and coexist with variable document shapes.

9
MCQhard

Refer to the exhibit. Why would an operation attempting to insert the document shown in the exhibit fail?

A.The '_id' field is invalid.
B.The field 'metadata' is a reserved keyword.
C.The field '$created' starts with a reserved character.
D.The value 'null' is not allowed for the 'last_login' field.
AnswerC

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.

Why this answer

The document contains a field named '$created'. In MongoDB, field names starting with a '$' symbol are reserved for internal query operators. When the database engine parses a document, it interprets fields beginning with '$' as instructions rather than data fields.

This naming conflict is a common trap for developers migrating legacy data or building generic metadata structures without validating field name constraints.

Exam trap

Test-takers frequently confuse reserved field names starting with a dollar sign with normal custom data fields, missing that the parser treats them as query operators.

10
MCQmedium

A developer is modeling a blog platform. Posts are read frequently, and each post has a small, bounded set of tags. The tags are always displayed with the post and are never queried independently across posts. The developer is deciding between embedding the tags as an array inside each post document versus storing them in a separate tags collection with references. Which design choice aligns with MongoDB document model guidance for this scenario?

A.Embed the tags as an array within each post document, since they are bounded, accessed together with the post, and not queried independently.
B.Store tags both embedded in posts and in a separate collection, keeping them synchronized manually, to satisfy both read and write paths.
C.Store tags in a separate collection and use a $lookup aggregation in every read, because aggregation pipelines are the only way to combine related data.
D.Store tags in a separate collection and reference them from posts, because normalization always reduces duplication and improves read performance.
AnswerA

Embedding is the recommended approach when the related data is bounded, is read together with the parent, and is not accessed on its own. An array of tags inside the post lets the application retrieve everything needed for rendering in a single read, avoiding a join. This matches the access pattern described and keeps the document model aligned with how the data is used.

Why this answer

MongoDB document modeling favors embedding when related data is bounded, is retrieved together with its parent, and is not queried on its own. The tags described fit all three conditions, so embedding them as an array in each post yields single-read retrieval and avoids join overhead. A separate collection would only be justified if tags needed independent querying or unbounded growth.

Exam trap

The trap here is applying relational normalization instincts and assuming a separate collection always improves performance, when in MongoDB the access pattern should drive the decision.

11
MCQeasy

A developer is designing a MongoDB collection to store user profiles. Each profile document includes fields for name, email, and an array of phone numbers. The developer wants to ensure that the email field is unique across all documents. Which MongoDB feature should be used to enforce this constraint?

A.Sharding the collection on the email field
B.Schema validation with $jsonSchema
C.Application-level check before insert
D.Unique index on the email field
AnswerD

A unique index on the email field ensures that no two documents can have the same email value. MongoDB will reject any insert or update that would create a duplicate key. This is the standard way to enforce uniqueness in a collection, and it works across all documents. It also improves query performance for lookups by email.

Why this answer

A unique index on the email field is the only reliable way to enforce uniqueness in MongoDB. It guarantees that no two documents can have the same email value, even under concurrent operations. Schema validation, sharding, and application-level checks cannot provide this guarantee.

The unique index also speeds up queries that filter by email.

Exam trap

The trap here is assuming that schema validation can enforce uniqueness, but validation rules operate per document and cannot reference other documents.

12
MCQmedium

A developer is building a MongoDB application to store user profiles. Each profile document includes a field `lastLogin` that records the exact date and time of the user's most recent login. The developer wants to ensure that this field is stored using the most appropriate BSON type for date and time values, allowing for efficient range queries and sorting. Which BSON type should be used for the `lastLogin` field?

A.Timestamp
B.Date
C.ObjectId
D.String
AnswerB

The BSON Date type stores a 64-bit integer representing milliseconds since the Unix epoch, making it ideal for storing exact points in time. It supports efficient range queries, sorting, and date aggregation operators. For a `lastLogin` field, using Date ensures correct temporal ordering and enables queries like finding users who logged in within the last 24 hours.

Why this answer

The BSON Date type is the standard for storing date and time values in MongoDB. It provides millisecond precision and integrates with query operators like `$gt`, `$lt`, and aggregation date operators. Using it for a `lastLogin` field ensures accurate temporal comparisons and efficient indexing.

Other types like String or Timestamp are either inefficient or semantically incorrect for application-level timestamps.

Exam trap

The trap here is confusing the BSON Timestamp type, which is for internal replication use, with the Date type that is meant for application date storage.

13
MCQmedium

A developer is working with a MongoDB collection that stores product data. Each product document has a 'price' field. The developer needs to find all products with a price greater than 100 and less than 200. Which query operator should be used?

A.$gte and $lte
B.$and with $gt
C.$in
D.$gt and $lt
AnswerD

The $gt (greater than) and $lt (less than) operators are used to specify a range condition. By combining them in a query like {price: {$gt: 100, $lt: 200}}, MongoDB returns documents where the price falls strictly between 100 and 200. This is the correct way to express an exclusive range.

Why this answer

To find documents where a field falls within an exclusive range, MongoDB provides the $gt and $lt operators. Combining them in a single query object on the same field applies both conditions. This is a common pattern for range queries and is efficient when an index exists on the field.

The other operators either include boundary values or are for different query types.

Exam trap

The trap here is mixing up inclusive and exclusive range operators; $gte/$lte would include the boundaries, which the scenario explicitly excludes.

14
MCQmedium

An application needs to store an e-commerce catalog where products have varying attributes such as clothing sizes or electronic specifications. You choose MongoDB for its dynamic schema. Which design approach best leverages the MongoDB document model for this use case?

A.Normalize product attributes into multiple separate collections linked by manual application references to enforce rigid schema constraints.
B.Serialize all product attributes into a single large binary blob string stored in a single generic text field inside the main document.
C.Embed the varying attributes directly within each product document using flexible subdocuments or arrays that match the specific item.
D.Enforce a strict static schema across all product documents using server-side validation rules that require every possible attribute key to be present.
AnswerC

Embedding varying attributes directly within each document leverages the dynamic nature of BSON. This structure allows the database to index and query specific attributes efficiently while keeping all relevant product details contained in a single fetch.

Why this answer

Storing variable attributes directly inside the document using flexible subdocuments or arrays allows efficient single-query retrieval of all product details. This harnesses the core advantage of the document model by keeping related data together, avoiding complex multi-table joins and matching the natural data access patterns of modern applications.

Exam trap

Candidates often assume normalization principles from relational databases still apply, mistakenly creating separate collections for every optional product attribute and performing application-level lookups.

15
MCQhard

A financial application stores transaction records in a MongoDB collection. Each transaction document includes a Decimal128 amount field and a Date field for the transaction time. A developer needs to query for transactions with amounts greater than 100.00 and times within the last 24 hours, and wants the queries to use indexes efficiently. Which statement about the document model and BSON types is correct for this scenario?

A.Range queries on Decimal128 fields are not supported; only equality queries can use an index on a Decimal128 field.
B.Decimal128 values are stored as strings, so range queries on the amount field require a text index rather than a numeric index.
C.Date values are stored as 64-bit integers representing milliseconds since the Unix epoch, and they can be indexed and compared with range operators.
D.Because Decimal128 and Date are both binary types, they cannot be used together in a compound index on the same collection.
AnswerC

BSON Date is a 64-bit signed integer counting milliseconds since the Unix epoch. It is a first-class type that supports comparison operators such as $gt and $lt, and it can be indexed. This allows efficient range queries on the transaction time field, which is exactly what the developer needs for finding transactions within the last 24 hours.

Why this answer

BSON Date is stored as a 64-bit integer of milliseconds since the Unix epoch, which makes it directly comparable and indexable for range queries. Decimal128 is a separate numeric type that also supports range comparisons and indexing. Together, they allow the application to filter by amount and time efficiently using appropriate indexes, without converting values to strings or avoiding range queries.

Exam trap

The trap here is assuming that Decimal128 must be treated as a string or that Date cannot be used in range queries, when both are indexable BSON types that support numeric and temporal comparisons.

16
MCQeasy

A developer is new to MongoDB and is examining a collection of documents. Each document contains fields like `name`, `age`, and `address`, where `address` is a nested document with `street`, `city`, and `zip`. The developer wants to query for all documents where the `city` in the nested `address` document is 'New York'. Which query correctly retrieves these documents?

A.db.collection.find({ $elemMatch: { 'address.city': 'New York' } })
B.db.collection.find({ address: { city: 'New York' } })
C.db.collection.find({ 'address.city': 'New York' })
D.db.collection.find({ address.city: 'New York' })
AnswerC

This query uses dot notation to target the `city` field within the nested `address` document. It correctly matches documents where the nested `city` value is 'New York', regardless of other fields in the subdocument. Dot notation is the standard way to query nested fields in MongoDB, allowing precise access to embedded document properties.

Why this answer

To query a nested field in MongoDB, you use dot notation within a string, such as `'address.city'`. This allows the query to match documents where the nested `city` field equals 'New York', regardless of other fields in the subdocument. The other options either perform an exact match on the entire subdocument, use invalid syntax, or misuse the `$elemMatch` operator.

Exam trap

The trap here is using an exact match on the nested document, which requires all fields to match exactly, rather than using dot notation to target a single field.

17
MCQmedium

A developer is designing a MongoDB collection to store sensor readings. Each reading document contains a sensorId, a timestamp, and a readings array of subdocuments with type and value fields. The application frequently queries for readings where the readings array contains a subdocument with type "temperature" and value greater than 30. Which document model feature allows the query to match elements within the array efficiently?

A.Multikey indexes, which are created automatically when an index is built on a field that contains an array, allow the query to match individual array elements.
B.The _id index, which is created on every collection, includes all array elements and can be used to match subdocument fields.
C.Capped collections, which store documents in insertion order, automatically index array elements for fast lookups.
D.Array flattening, which merges all subdocuments into a single document, allows the query to treat the readings array as a flat set of fields.
AnswerA

When an index is created on a field that holds an array, MongoDB creates a multikey index with separate index entries for each array element. This allows queries that filter on array elements, such as readings.type and readings.value, to use the index efficiently. The server can match the specific subdocument conditions without scanning the entire collection, which fits the sensor reading scenario.

Why this answer

A multikey index is created when an index is built on a field containing an array. MongoDB generates an index entry for each array element, so queries that filter on subdocument fields within the array can use the index. This allows the sensor reading query to match temperature readings above 30 efficiently, as long as an appropriate index exists on the readings field.

Exam trap

The trap here is thinking that arrays are automatically indexed or that the _id index covers array elements, when in fact a dedicated multikey index on the array field is required.

18
MCQmedium

A developer stores product documents in a MongoDB collection. Some documents include a nested details object with a warranty subfield, while others do not. The developer needs to retrieve only the documents where details.warranty equals the string "2 years". Which query correctly targets that nested field?

A.db.products.find({ details: { warranty: "2 years" } })
B.db.products.find({ $where: "this.details.warranty === '2 years'" })
C.db.products.find({ "details.warranty": "2 years" })
D.db.products.find({ details: { $elemMatch: { warranty: "2 years" } } })
AnswerC

Dot notation reaches into embedded documents, so the path details.warranty matches the warranty field inside the details object. Quoting the path is required because it contains a dot. This query returns exactly the documents whose nested warranty value equals the string, which is the requested result and the standard way to query embedded fields in MongoDB.

Why this answer

Dot notation is the correct way to query a field inside an embedded document. Writing the path as a quoted string, such as details.warranty, tells MongoDB to look inside the details object for the warranty field and compare its value. This approach uses indexes when available and returns only documents whose nested field equals the requested value.

Exam trap

The trap here is writing the nested field as an embedded document equality match, which requires the entire subdocument to match exactly and silently misses documents with extra fields.

19
MCQmedium

A developer is working with a MongoDB collection that stores sensor readings. Each document contains a timestamp, sensor ID, and a nested object 'readings' with fields like 'temperature', 'humidity', and 'pressure'. The developer needs to query for all documents where the temperature reading exceeds 30 degrees Celsius. Which query correctly retrieves these documents?

A.db.sensors.find( { $where: "this.readings.temperature > 30" } )
B.db.sensors.find( { "readings.temperature": { $gt: 30 } } )
C.db.sensors.find( { readings: { temperature: { $gt: 30 } } } )
D.db.sensors.find( { "readings": { $elemMatch: { temperature: { $gt: 30 } } } } )
AnswerB

This query uses dot notation to access the nested field 'temperature' within the 'readings' object and applies the $gt operator to find values greater than 30. Dot notation is the correct way to query nested fields in MongoDB, making this the accurate query for the scenario.

Why this answer

MongoDB uses dot notation to query nested fields within documents. The query with "readings.temperature" and $gt correctly targets the nested temperature value. The other options either misinterpret the structure, use array-specific operators incorrectly, or rely on inefficient JavaScript evaluation, making them unsuitable for this scenario.

Exam trap

The trap here is confusing nested object queries with array queries, leading to the misuse of $elemMatch or exact subdocument matching.

20
MCQmedium

A developer is building a MongoDB application that tracks server metrics. Each metric document must include a timestamp, and the application frequently queries metrics for a specific server within a date range. The developer wants to ensure that the timestamp field is stored in a way that supports efficient range queries and sorting. Which BSON data type should the timestamp field use?

A.String
B.Timestamp
C.Date
D.Long
AnswerC

The BSON Date type stores a 64-bit integer representing milliseconds since the Unix epoch (January 1, 1970). This numeric representation allows MongoDB to efficiently compare and sort dates, making it ideal for range queries on timestamps. Using Date ensures that queries like finding metrics between two dates are optimized and accurate, and it integrates seamlessly with MongoDB's query operators such as $gt and $lt.

Why this answer

The BSON Date type is the correct choice because it stores time as a 64-bit integer (milliseconds since epoch), enabling efficient range queries and sorting. It is the standard type for timestamps in MongoDB applications and is fully supported by query and aggregation operators. The Timestamp type is reserved for internal use, while String and Long would require manual handling and lack native date functionality.

Exam trap

The trap here is confusing the BSON Timestamp type, which is for internal replication, with the Date type intended for application timestamps.

21
MCQhard

A financial application stores transaction documents in a MongoDB collection. Each document includes fields such as 'transactionId', 'amount', 'currency', and 'timestamp'. The application requires that the 'amount' field always be present and be a double, and that 'currency' be one of a predefined list of ISO codes. Which MongoDB feature should the developer use to enforce these requirements at the database level?

A.Application-level validation using Mongoose schema definitions.
B.Unique indexes on the 'amount' and 'currency' fields.
C.Sharding the collection on the 'currency' field.
D.Schema validation using JSON Schema with $jsonSchema operator.
AnswerD

MongoDB supports schema validation through the $jsonSchema operator, which allows defining rules such as required fields, BSON type constraints, and enum values. This enforces the requirements at the database level, ensuring data integrity regardless of the application layer, making it the correct choice.

Why this answer

Schema validation with $jsonSchema allows developers to specify required fields, BSON types, and allowed values, enforcing data integrity directly in MongoDB. This is ideal for ensuring that 'amount' is always a double and 'currency' is from a predefined list. Other options either provide weaker guarantees or are unrelated to validation.

Exam trap

The trap here is assuming that application-level validation or indexes can enforce complex data integrity rules, when only database-level schema validation provides that guarantee.

22
MCQhard

An application stores customer profiles in a MongoDB collection. A developer notices that documents created by different services have inconsistent shapes: some use a string for phone, others an array of strings, and some omit the field entirely. The team wants to enforce a consistent structure for new writes while still allowing existing documents to remain. Which MongoDB feature should they use?

A.A unique index on the phone field, which forces every document to use the same BSON type for that field.
B.A partial index with a filter expression that excludes documents lacking the phone field.
C.A change stream that watches the collection and rejects documents whose shape differs from a template.
D.A JSON Schema validator attached to the collection with the $jsonSchema operator and validationLevel set to strict.
AnswerD

$jsonSchema lets the team declare required fields and BSON types, and attaching it with collMod applies it to the collection. Setting validationLevel to strict enforces the rules on all inserts and updates, including existing documents when they are modified, which matches the goal of consistent new writes while leaving untouched documents in place. This is the native MongoDB mechanism for schema validation.

Why this answer

MongoDB supports schema validation through the $jsonSchema operator, configured on a collection with collMod. Setting validationLevel to strict applies the rules to all inserts and updates, so new writes must match the declared structure. Existing documents that are not modified remain untouched, which satisfies the requirement to leave current data as is while enforcing consistency going forward.

Exam trap

The trap here is assuming that indexes enforce document structure, when in MongoDB only schema validation rules applied to the collection can reject writes that do not match the declared shape.

23
Multi-Selectmedium

A developer is reviewing the characteristics of MongoDB documents. Which two of the following statements are accurate? (Choose two.)

Select 2 answers
A.Documents are stored in a human-readable JSON format on disk.
B.Each document must have a unique _id field, which can be of any BSON data type except an array.
C.Field names in a document can contain the null character.
D.Documents in the same collection must have the same set of fields.
E.The maximum size of a BSON document is 16 MB.
AnswersB, E

Every document requires a unique _id field that serves as the primary key. The _id can be any BSON type except an array, allowing flexibility such as using ObjectId, strings, or numbers. This uniqueness ensures that each document can be uniquely identified within a collection, and MongoDB automatically creates an index on _id.

Why this answer

The maximum BSON document size is 16 MB, and every document must have a unique _id field that can be any BSON type except an array. Documents in a collection need not share the same fields, they are stored in BSON not JSON, and field names cannot contain null characters.

Exam trap

The trap here is assuming that documents in a collection must have a uniform structure, but MongoDB's schema flexibility allows varied fields.

24
Multi-Selectmedium

A developer is reviewing how MongoDB represents and stores data at the document level. Which TWO statements accurately describe the behavior of the BSON format and MongoDB documents? (Choose two.)

Select 2 answers
A.Field order within a BSON document is not preserved, so queries that depend on field order will not work consistently.
B.BSON documents are stored as plain text JSON on disk to simplify backup and restore operations.
C.The maximum size of a single BSON document in MongoDB is 16 MB, and this limit applies to the document as stored on the server.
D.BSON supports additional data types beyond JSON, such as ObjectId, Date, and Binary, which are stored as distinct type codes.
E.A MongoDB document can contain fields with duplicate names, and the server preserves both values when the document is stored.
AnswersC, D

MongoDB enforces a 16 MB limit on each BSON document. The limit is checked when documents are inserted or updated, and it applies to the stored document size. Applications that need to store larger payloads should use GridFS, which splits data across multiple documents. This limit is a fundamental constraint of the document model.

Why this answer

BSON is a binary-encoded format that extends JSON with types such as ObjectId, Date, and Binary, each identified by a type code. MongoDB also enforces a 16 MB maximum document size, which affects how applications design their data model. These two facts are central to understanding how documents are represented and stored, and they explain why BSON is used rather than plain JSON.

Exam trap

The trap here is assuming BSON is just text JSON with extra types, when it is actually a binary format with its own type codes and a hard 16 MB document size limit.

25
MCQmedium

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?

A.Normalize the data by creating a separate collection for child documents.
B.Embed child documents directly as an array within the parent document.
C.Store the child data in a separate database to isolate the write load.
D.Use a flat structure and duplicate parent information in every child document.
AnswerB

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.

Why this answer

The embedding pattern is preferred for one-to-many relationships where children are always retrieved alongside the parent. This pattern minimizes the number of required read operations by ensuring all necessary data is located within a single document. This reduces latency and eliminates the need for expensive application-level joins, resulting in highly performant read operations for typical read-heavy application workflows.

Exam trap

Candidates frequently try to normalize every relationship into separate collections, overlooking the performance benefits of embedding for one-to-many relationships.

26
MCQhard

A financial application stores transactions in a MongoDB collection. Each transaction document includes a 'timestamp' field. The application needs to query transactions for a specific day, and the queries must be efficient. Which indexing strategy is most appropriate?

A.Create a hashed index on the 'timestamp' field
B.Create a compound index on {timestamp: 1, _id: 1}
C.Create a text index on the 'timestamp' field
D.Create a single-field index on the 'timestamp' field
AnswerD

A single-field index on 'timestamp' allows MongoDB to efficiently locate documents within a date range, such as a specific day. Since the query filters on timestamp, this index directly supports the query pattern, reducing the number of documents scanned. It is the most straightforward and effective solution for range queries on a single field.

Why this answer

For efficient range queries on a single field, a single-field index is the correct choice. It allows MongoDB to quickly find documents with timestamps within the desired range. Compound indexes can also work but are unnecessary here, and other index types like text or hashed do not support range queries on dates.

The single-field index provides the best balance of performance and simplicity.

Exam trap

The trap here is assuming that any index on the timestamp field will work, but hashed indexes do not support range queries, and text indexes are for strings, not dates.

27
MCQmedium

A developer is building an inventory system for a hardware store. Each item document needs to store the product's name, a unique SKU, the quantity on hand, and a list of compatible replacement part numbers. The developer wants to ensure that the `sku` field is always present and is a string, while still allowing other fields to vary between item types. Which MongoDB feature should the developer use to enforce this requirement?

A.The `$exists` query operator in all read operations
B.A unique index on the `sku` field
C.JSON Schema validation with the `$jsonSchema` operator in a collection validator
D.Storing the `sku` in a separate collection and using `$lookup`
AnswerC

Collection validators using `$jsonSchema` let you require specific fields and types, such as `sku` as a string, while leaving other fields flexible. This directly enforces the rule at the database level for every insert or update, which matches the developer's need to guarantee `sku` presence and type without restricting the rest of the document shape.

Why this answer

The requirement is to enforce a specific field and type at write time while allowing other fields to vary. MongoDB's schema validation with `$jsonSchema` is designed for exactly this: you can specify required fields and BSON types in a validator, and the server rejects documents that do not comply. This keeps the collection flexible for other fields but guarantees the `sku` contract.

Exam trap

The trap here is assuming that a unique index also enforces field presence and type, when it only enforces uniqueness among existing values.

28
MCQeasy

When designing a document model, which factor is most important for determining whether to embed or reference data?

A.The total number of documents in the collection.
B.The application's data access patterns.
C.The memory limit of the database server.
D.The complexity of the data's object-oriented relationships.
AnswerB

Access patterns define the query load. By modeling data to fit how it is queried, you reduce the need for joins and multiple roundtrips. Embedding is ideal for data that is always accessed together, while referencing is better for avoiding large, oversized documents that are rarely fully needed.

Why this answer

The access pattern—specifically how often data is retrieved and how it is used—is the deciding factor. If data is usually needed together, embedding provides the best read performance. If data is accessed independently or the child data grows without bound, referencing is more appropriate.

Aligning the model with access patterns is the core tenet of MongoDB performance optimization and design.

Exam trap

Candidates often choose based on data relationship size or normalization rules from relational databases, ignoring that MongoDB design must prioritize how the application specifically queries and retrieves the data.

29
MCQhard

A development team is designing a MongoDB collection to store sensor readings. Each reading document contains a `sensorId`, a `timestamp`, and a `value`. The team expects billions of readings and needs to optimize for fast queries that retrieve the latest reading for a specific sensor. They decide to use a compound index. Which index key order best supports this query pattern?

A.{ timestamp: 1, sensorId: 1 }
B.{ value: 1, sensorId: 1 }
C.{ sensorId: 1, value: 1 }
D.{ sensorId: 1, timestamp: -1 }
AnswerD

Placing sensorId first allows the index to quickly locate all readings for a specific sensor. The descending timestamp then orders those readings from newest to oldest, so the first entry for that sensor is the latest reading. This supports an efficient query using `find({ sensorId: X }).sort({ timestamp: -1 }).limit(1)` with a covered index scan.

Why this answer

The optimal compound index for retrieving the latest reading per sensor is `{ sensorId: 1, timestamp: -1 }`. This allows MongoDB to seek directly to the sensor's entries and return them in descending time order, so the first result is the most recent. It also supports equality on sensorId and sort on timestamp, enabling an efficient, non-blocking query.

Exam trap

The trap here is assuming that the timestamp field should come first because it is used in sorting, but the equality filter on sensorId must precede the sort field in the index.

30
MCQmedium

A developer is working with a MongoDB collection that stores product data. The collection has documents with a field 'price' that is sometimes stored as a double and sometimes as a string, due to inconsistent data entry. A query is run to find all products with a price greater than 100. What is the expected behavior of this query?

A.The query will return only documents where 'price' is a double greater than 100.
B.The query will return an error because of the mixed data types in the 'price' field.
C.The query will return documents where 'price' is a string greater than '100' lexicographically, as well as doubles greater than 100.
D.The query will return all documents where 'price' is greater than 100, regardless of whether it is a double or string.
AnswerA

MongoDB queries enforce type bracketing: comparison operators like $gt only match values of the same BSON type as the query operand. Since 100 is a double, only double values are compared; string values are not converted and thus excluded. This behavior ensures consistent comparisons but can lead to unexpected results if data types are mixed.

Why this answer

MongoDB uses type bracketing for comparison operators: only values of the same BSON type as the operand are considered. Since 100 is a double, only double prices greater than 100 are returned. Strings are not converted, and no error occurs.

This underscores the importance of consistent data types in a collection.

Exam trap

The trap here is assuming that MongoDB will coerce types or compare across types, but it strictly adheres to BSON type bracketing for queries.

31
MCQeasy

Which of the following describes the behavior of the BSON format within MongoDB?

A.It is a text-based format identical to JSON but with limited character support.
B.It supports a subset of data types compared to standard JSON.
C.It is a binary-encoded serialization of JSON documents.
D.It requires manual conversion by the driver for every read operation.
AnswerC

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.

Why this answer

BSON (Binary JSON) is the primary data storage format for MongoDB. It extends JSON by providing additional types like Date and BinData while being optimized for fast traversal and efficient serialization. Understanding BSON is critical because it dictates how data is physically stored on disk and read into memory, ensuring that MongoDB maintains its high-performance characteristics while handling complex data structures.

Exam trap

Candidates often assume BSON is just a text-based format like JSON, failing to recognize the binary encoding and type-specific metadata that make it efficient for database operations.

32
MCQmedium

A developer is building a MongoDB application to store sensor readings from thousands of IoT devices. Each reading document contains a device ID, timestamp, and an array of up to 100 numeric values. The developer wants to minimize document size and storage overhead while preserving the ability to query individual readings. Which BSON data type should be used to store the numeric values array to achieve the smallest document size?

A.Store the values as a BSON array of Decimal128.
B.Store the values as a BSON array of doubles.
C.Store the values as a BSON binary subtype 0 (generic binary) using the BinData type.
D.Store the values as a BSON array of 32-bit integers (int).
AnswerD

BSON 32-bit integers occupy 4 bytes each, half the size of a double. For sensor readings that are whole numbers, this reduces document size significantly while preserving array structure and allowing direct queries on elements. The int type is fully supported by MongoDB drivers and maintains indexability, making it the most efficient choice for this scenario.

Why this answer

For integer sensor readings, the 32-bit integer BSON type offers the best balance of compactness and queryability. It uses half the space of a double and allows direct indexing and querying of array elements, unlike binary blobs. Decimal128 and doubles are unnecessarily large for whole numbers, and BinData would require custom deserialization.

Exam trap

The trap here is assuming that the default numeric type (double) is always the most efficient, when smaller integer types can significantly reduce document size for whole numbers.

33
MCQmedium

A development team is migrating a legacy application to MongoDB. They need to store product inventory data that includes a unique identifier, a name, a price, and a list of warehouse locations with quantities. The team wants to minimize the number of queries required to retrieve all information for a product. Which MongoDB document design approach best meets this requirement?

A.Embed the warehouse locations as an array of subdocuments within the product document.
B.Store warehouse locations in a separate collection and reference them by ObjectId from the product document.
C.Normalize the data into multiple collections: products, warehouses, and inventory, with foreign key relationships.
D.Store each warehouse location as a separate document in the same collection as products.
AnswerA

Embedding warehouse locations as an array within the product document stores all related data in a single document. This allows the application to retrieve the complete product information, including inventory per warehouse, with a single query, minimizing the number of queries and improving read performance for this access pattern.

Why this answer

Embedding related data within a single document aligns with MongoDB's document model and supports atomic operations and efficient reads. By embedding warehouse locations as an array, the application retrieves the full product inventory in one query, which is optimal for this access pattern. Referencing or normalizing would require additional queries or application-side joins, increasing latency and complexity.

Exam trap

The trap here is assuming that referencing is always better for one-to-many relationships, but embedding is preferred when data is accessed together and query minimization is key.

34
MCQmedium

What is the primary benefit of the 'Bucket Pattern' in MongoDB data modeling?

A.It eliminates the need for any indexing on the collection.
B.It keeps document sizes within reasonable limits for time-series data.
C.It forces data normalization across multiple sharded clusters.
D.It automatically migrates old data to archival storage systems.
AnswerB

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.

Why this answer

The Bucket Pattern is used to avoid the 'unbounded array' problem, where a single document could grow indefinitely. By grouping data into manageable 'buckets' (e.g., one document per day of sensor data), the pattern keeps document sizes manageable, ensures efficient indexing, and optimizes write performance. This approach prevents documents from hitting the 16MB limit while maintaining query speed for time-series data.

Exam trap

Students often store continuous time-series data in a single unbounded array, hitting the 16MB document size limit instead of using the Bucket Pattern.

35
MCQeasy

Which of the following describes the 'schema-flexible' nature of MongoDB?

A.All documents must have a predefined structure determined by the first document inserted.
B.Documents can have different fields, and the structure can change over time.
C.The database automatically flattens all nested documents upon insertion.
D.Schema enforcement can only be achieved by using third-party database proxies.
AnswerB

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.

Why this answer

Schema-flexibility means that documents in the same collection do not need to have the same fields or structure. This allows developers to iterate quickly, as adding new fields or changing data structures doesn't require modifying existing data or taking the database offline. This is a fundamental departure from rigid, table-based relational schemas that mandate defined structures before any data can be inserted.

Exam trap

Students often believe schema flexibility means documents in a collection can have completely unrelated business domains, rather than varying structures for similar entities.

36
MCQeasy

A developer is designing a MongoDB collection to store user profiles for a mobile application. Each profile document may contain a varying set of optional fields, such as 'phoneNumber', 'profilePicture', and 'preferences'. The developer wants to ensure that the database can efficiently store and query these documents without requiring a predefined schema. Which MongoDB feature best supports this requirement?

A.The use of strict schema validation rules enforced at the collection level.
B.The ability to store data in a fixed tabular format with rows and columns.
C.The requirement to define all possible fields in advance using a schema definition language.
D.The document model, which allows each document in a collection to have a different structure.
AnswerD

MongoDB's document model stores data as BSON documents, and each document in a collection can have a different set of fields. This schema-flexible design directly supports storing user profiles with varying optional fields without requiring schema migrations or predefined columns, making it the correct choice for this scenario.

Why this answer

The document model in MongoDB allows each document to have its own structure, meaning fields can vary from one document to another. This is ideal for user profiles with optional fields because developers can add or omit fields without altering a global schema. The other options impose rigid structures that are not part of MongoDB's core flexibility.

Exam trap

The trap here is assuming that MongoDB requires a predefined schema like relational databases, when in fact its document model is schema-flexible.

37
MCQeasy

A developer is writing a Node.js script that inserts a user document into a MongoDB 7.0 collection. The document includes an _id field whose value is generated by the driver as an ObjectId. A teammate asks why the _id field is present even though the insertOne call did not specify it. Which statement best explains the behavior of _id in MongoDB?

A.The _id field is added by the mongod server after the insert completes, and the client must run a find to retrieve the generated value.
B.The _id field is optional and is only populated when the collection has a unique index defined by the developer.
C.The _id field is only required for capped collections and time series collections, while normal collections allow documents without it.
D.The _id field is mandatory in every document, and if the client omits it the driver generates an ObjectId before sending the insert.
AnswerD

MongoDB requires a unique _id in every document stored in a collection. When an application does not supply one, the official drivers generate an ObjectId client-side and include it in the insert command, so the server receives a document that already has an _id. This is why the field appears even though the code never set it explicitly.

Why this answer

MongoDB mandates a unique _id in every stored document and automatically builds a unique index on that field. Official drivers generate an ObjectId on the client when the application does not provide one, so the field is present in the inserted document without explicit developer action. This guarantees each document can be uniquely identified and located efficiently.

Exam trap

The trap here is assuming _id is optional or that the server generates it after the insert, rather than recognizing that the driver creates the ObjectId client-side before sending the command.

38
MCQmedium

A developer is reviewing a MongoDB collection that stores blog posts. Each post document has a field 'tags' that is an array of strings. The developer wants to find all posts that have both 'mongodb' and 'database' in the tags array. Which query correctly retrieves these documents?

A.{ tags: { $in: ["mongodb", "database"] } }
B.{ tags: { $all: ["mongodb", "database"] } }
C.{ tags: { $elemMatch: { $eq: "mongodb", $eq: "database" } } }
D.{ tags: ["mongodb", "database"] }
AnswerB

The $all operator matches documents where the array field contains all the specified elements. In this case, it will return posts that have both 'mongodb' and 'database' in the tags array, regardless of order or additional elements. This is the correct and efficient way to query for multiple elements in an array.

Why this answer

The $all operator is designed to match arrays that contain all specified elements, making it the correct choice for finding posts with both 'mongodb' and 'database' tags. The $in operator matches any of the elements, the exact array match is too strict, and $elemMatch is for conditions on a single element. Only $all satisfies the requirement.

Exam trap

The trap here is confusing $all with $in; $in matches any of the values, while $all requires all values to be present.

Ready to test yourself?

Try a timed practice session using only Mongodb Overview Document Model questions.