Courseiva

CCNA CRUD Operations Questions

33 questions · CRUD Operations · All types, answers revealed

1
MCQmedium

Refer to the exhibit. What is the effect of the 'writeConcern' parameter in this operation?

A.It forces the update to occur only on the primary node.
B.It ensures the data is replicated to most nodes before acknowledgment.
C.It only updates documents that have a majority of fields set.
D.It makes the update operation read-only.
AnswerB

Setting w: 'majority' ensures that the write operation is committed to a majority of the voting members in the replica set. This provides a high level of data durability, ensuring that if a failover occurs, the update will persist on the newly elected primary node.

Why this answer

The write concern {w: 'majority'} ensures that the operation is only acknowledged after it has been written to a majority of the replica set members. This is essential for data durability and preventing data loss in the event of a primary node failover. It provides a stronger guarantee than the default 'w: 1' by ensuring that data is replicated before the application proceeds.

Exam trap

Candidates often assume 'majority' write concern means the data is written to all nodes. They fail to realize it only requires a quorum of voting members.

2
MCQmedium

What happens if you run an update operation with the $set operator on a field that does not yet exist in the document?

A.The update fails with an error.
B.The field is created with the new value.
C.The update is ignored.
D.The entire document is replaced.
AnswerB

When $set targets a field that is currently absent from the document, MongoDB inserts that field and assigns it the provided value. This makes it trivial to perform incremental schema updates, enabling the application to store new data points immediately without requiring a full database rewrite.

Why this answer

MongoDB is schema-flexible, meaning it will create the field if it is missing during an update operation. The $set operator is intelligent enough to add the field with the specified value, which simplifies code by eliminating the need for pre-checks or initialization logic. This is a core strength of the document model that allows for evolving data requirements without requiring explicit database migrations.

Exam trap

Many candidates falsely believe that running an update with $set on a missing field will throw an error or require prior schema definition.

3
MCQmedium

A retail application stores product documents in the `products` collection. Each document has an `inventory` array of embedded subdocuments, for example: `{ _id: 1, name: "Widget", inventory: [ { sku: "A1", qty: 5 }, { sku: "B2", qty: 8 } ] }`. The warehouse team needs to increase the `qty` of the subdocument with `sku: "B2"` by 3 for the product with `_id: 1`. Which update operation accomplishes this?

A.db.products.updateOne( { _id: 1, "inventory.sku": "B2" }, { $inc: { "inventory.0.qty": 3 } } )
B.db.products.updateOne( { _id: 1, "inventory.sku": "B2" }, { $set: { "inventory.$.qty": "3" } } )
C.db.products.updateOne( { _id: 1, "inventory.sku": "B2" }, { $inc: { "inventory.$.qty": 3 } } )
D.db.products.updateOne( { _id: 1 }, { $inc: { "inventory.qty": 3 } } )
AnswerC

This correctly uses the positional `$` operator. The query identifies the array element whose `sku` equals "B2", and the positional operator updates the `qty` field of the matched array element only. This is the standard MongoDB pattern for updating a specific embedded subdocument in an array without replacing the whole array.

Why this answer

The positional `$` operator updates the first array element that matches the query condition. Pairing `"inventory.sku": "B2"` in the filter with `"inventory.$.qty"` in the update ensures only the subdocument with that SKU is modified. Using `$inc` performs the required arithmetic and preserves the numeric field type, which is essential for inventory counts.

Exam trap

The trap here is assuming that dot notation like `inventory.qty` automatically targets array element fields, when in fact it requires the positional operator to match a specific subdocument.

4
MCQeasy

A developer needs to insert a document into the inventory collection and wants the operation to fail with a duplicate key error if a document with the same value for the sku field already exists. The sku field has a unique index. Which insert method and option combination achieves this with the least code?

A.db.inventory.insertOne( { sku: "A100", qty: 5 } )
B.db.inventory.updateOne( { sku: "A100" }, { $set: { qty: 5 } }, { upsert: true } )
C.db.inventory.insertMany( [ { sku: "A100", qty: 5 } ], { bypassDocumentValidation: true } )
D.db.inventory.insertOne( { sku: "A100", qty: 5 }, { ordered: false } )
AnswerA

insertOne inserts the document and, because sku has a unique index, a duplicate value causes a duplicate key error to be thrown. This is the simplest correct approach: no extra option is needed. The unique index itself enforces the constraint, so the operation fails as required when a duplicate sku is present.

Why this answer

A unique index on sku is what enforces the duplicate constraint. A plain insertOne is sufficient: if the sku already exists, the server returns a duplicate key error. The ordered option is only relevant for multi-document inserts, upsert would update instead of fail, and bypassDocumentValidation only affects schema validation, not unique indexes.

Exam trap

The trap here is thinking that an insert option is required to enforce uniqueness, when the unique index itself already causes the duplicate key error.

5
MCQmedium

Which operator is best used to add an element to an array only if it does not already exist?

A.$push
B.$set
C.$addToSet
D.$each
AnswerC

This operator is specifically designed to treat an array as a mathematical set. It ensures uniqueness by verifying the element's absence before insertion. This atomic behavior is essential for maintaining clean data without the overhead of client-side validation logic or complex multi-step database interactions.

Why this answer

The $addToSet operator is the standard MongoDB tool for array manipulation when uniqueness is required. It ensures that the specified value is added to the array only if it is not currently present. This prevents duplicate entries without requiring the application to perform a read-then-write check, making it an atomic and highly performant operation for managing sets within document-based data structures.

Exam trap

Candidates often suggest using $push in combination with application-level logic to check for duplicates, failing to recognize that $addToSet handles this requirement natively and atomically in the database.

6
Multi-Selectmedium

A DBA is reviewing update operations that use the upsert option. Which TWO statements about upsert behavior in MongoDB are correct? (Choose two.)

Select 2 answers
A.If no document matches the filter, upsert inserts a new document based on the filter and the update operators.
B.Upsert cannot be used with update operators that modify array elements, such as $push.
C.If multiple documents match the filter, upsert updates all of them and inserts no new document.
D.Upsert always requires a unique index on the filter fields to avoid duplicate inserts.
E.If the filter contains only non-equality operators, the inserted document may not contain those fields.
AnswersA, E

When no document matches, the server constructs a new document from the equality conditions in the filter and the fields specified by update operators such as $set. This is the core behavior of upsert and is why it is useful for idempotent writes. The inserted document reflects both the filter's equality fields and the update's modifications.

Why this answer

Upsert inserts a new document when the filter matches nothing, building it from equality conditions in the filter plus the update operators. Non-equality operators do not contribute fields, so the inserted document may lack the filtered field. A unique index is recommended to prevent duplicate inserts from concurrent upserts, but it is not mandatory.

Array operators such as $push are allowed in upserts.

Exam trap

The trap here is assuming that every field in the filter, including range conditions, is copied into the upserted document, when only equality conditions are used.

7
MCQmedium

A collection called events stores documents with an array field named tags. You need to remove all occurrences of the string "obsolete" from the tags array in every document where the array contains that value, without affecting other elements. Which update operator should you use?

A.$pull
B.$unset
C.$pop
D.$set
AnswerA

$pull removes all elements from an array that match a specified condition or value. Applied with a filter matching documents whose tags array contains "obsolete", it deletes every occurrence of that string while preserving all other tags. This is precisely the operator designed for removing array elements by value.

Why this answer

$pull is the array update operator that removes all elements matching a value or condition. Filtering on documents where tags contains "obsolete" and applying $pull deletes every such occurrence while leaving other tags intact. $unset removes whole fields, $pop removes positional elements, and $set replaces values rather than selectively removing matches.

Exam trap

The trap here is confusing field removal with array element removal, assuming $unset can delete a value from inside an array.

8
MCQeasy

When using the find() method, which cursor modifier is used to skip a specific number of documents before returning results?

A..offset()
B..limit()
C..skip()
D..next()
AnswerC

The skip() method is the correct cursor modifier to ignore a specified number of documents. It allows developers to paginate through large collections by defining the starting offset. When combined with sort() and limit(), it provides a reliable way to retrieve subsets of data for user interfaces.

Why this answer

The skip() method is the standard cursor modifier used to bypass a set number of initial documents in a result set. It is essential for implementing pagination in applications, often used in conjunction with limit() to fetch specific pages of data. Understanding its impact on performance is vital, as skipping large numbers of documents can be expensive for the database engine to process.

Exam trap

Candidates often confuse skip() with limit(), or believe that skip() is an efficient way to access deep pages of data, ignoring the performance cost of scanning skipped documents.

9
MCQhard

What happens when you perform a find() query on a collection where the projection includes both an inclusion and an exclusion for different fields?

A.The query returns an error.
B.The inclusion takes precedence over the exclusion.
C.The exclusion takes precedence over the inclusion.
D.It returns the intersection of both fields.
AnswerA

MongoDB forbids mixing inclusion and exclusion in a single projection, as it creates ambiguity about which fields should be returned. The database server will explicitly return an error when it detects this configuration, forcing the developer to choose a consistent projection strategy for the requested fields.

Why this answer

MongoDB enforces strict rules regarding field projection. You cannot mix inclusions and exclusions in the same projection object, with the exception of the _id field. This design choice ensures predictable behavior for the result set.

Understanding this limitation is important for developers when they need to fetch specific subsets of data while omitting others, as it prevents common errors during query construction.

Exam trap

Candidates often assume that mixing field inclusions and exclusions works as long as they apply to different fields, missing the rule that errors out.

10
MCQmedium

You are updating a document in the `products` collection. The document has an array field `tags`. You need to add the tag "sale" to the array only if it does not already exist, and you want to ensure that no duplicate tags are added even if multiple updates run concurrently. Which update operator should you use?

A.$addToSet with $each
B.$push
C.$addToSet
D.$set
AnswerC

$addToSet adds a value to an array only if it does not already exist in the array. It is idempotent and safe for concurrent updates because it checks for the value's presence as part of the atomic update. This ensures the tag "sale" is added only once, preventing duplicates.

Why this answer

$addToSet is designed to add a value to an array only if it is not already present, making it the correct operator for ensuring uniqueness. It performs this check atomically, so concurrent updates will not introduce duplicates. $push would append duplicates, $set would replace the array, and $addToSet with $each is overkill for a single value.

Exam trap

The trap here is thinking $push can be used with a condition, or that $addToSet with $each is required for a single value.

11
MCQhard

Refer to the exhibit. What is the impact of this operation on the document?

A.It deletes the 'qty' field and creates a new 'quantity' field with the same value.
B.It fails because 'qty' is not a field in the document.
C.It replaces the entire document with a new one containing only the quantity field.
D.It creates a new collection named 'quantity'.
AnswerA

The $rename operator logically renames a field. It updates the key name while keeping the value intact. This is an efficient way to refactor document structures when field names need to be updated to match new application requirements or to maintain consistent naming conventions across the dataset.

Why this answer

The $rename operator updates the name of a field within a document. It is atomic at the document level. If the field 'qty' exists, it is renamed to 'quantity'.

If 'qty' does not exist, the operation does nothing. This is useful for schema migrations or refactoring data models without needing to delete and re-insert the document, which preserves the original _id and other field values.

Exam trap

Candidates assume $rename creates a copy of the data. They often forget that the original field is completely removed and its value moved to the new field name.

12
MCQeasy

A DBA is reviewing a slow query on the `orders` collection. The query is: `db.orders.find( { status: "shipped", total: { $gt: 100 } } )`. The collection has an index on `{ status: 1, total: 1 }`. Which statement best describes how MongoDB will use this index to satisfy the query?

A.The index will only be used for `status`, and `total` will be filtered in memory because range conditions cannot use an index.
B.The index will be used, but only if the query includes a sort on `total` to enforce index order.
C.The index will not be used because the query includes a range condition on `total`.
D.The index will be used to filter both `status` and `total` because the index prefix matches the equality condition and the range condition.
AnswerD

The compound index `{ status: 1, total: 1 }` has an equality field first and a range field second. MongoDB can use the index to match `status: "shipped"` exactly and then scan the index for `total > 100` within that status. This is the optimal use of a compound index for this query pattern.

Why this answer

A compound index with an equality field followed by a range field is ideal for queries that filter on both. MongoDB will use the index to seek to the equality value and then scan the range on the second field. This minimizes document examinations and is the expected behavior for the given index and query.

Exam trap

The trap here is believing that range conditions cannot leverage indexes or that a sort is required for index usage.

13
MCQmedium

You are maintaining an inventory collection where each document has a field named `stock` (integer). A nightly job needs to atomically decrement `stock` by 1 for the document with `sku: "A100"` and also insert the current timestamp into a `lastUpdated` field in the same operation, without overwriting any other fields. Which update operation should you use?

A.db.inventory.replaceOne({ sku: "A100" }, { stock: 0, lastUpdated: new Date() })
B.db.inventory.updateOne({ sku: "A100" }, { $set: { stock: stock - 1, lastUpdated: true } })
C.db.inventory.updateOne({ sku: "A100" }, { $inc: { stock: -1 }, $currentDate: { lastUpdated: true } })
D.db.inventory.updateMany({ sku: "A100" }, { $inc: { stock: -1 }, $set: { lastUpdated: new Date() } })
AnswerC

This uses updateOne with the $inc operator to decrement stock by 1 and $currentDate to set lastUpdated to the current date/time, all in a single atomic update. Both fields are modified without affecting other existing fields, exactly matching the requirement to atomically decrement and timestamp the document.

Why this answer

The $inc operator atomically increments or decrements a field by a specified amount, and $currentDate sets a field to the current date/time. Combining them in a single updateOne call ensures both modifications happen atomically on the matched document without altering other fields. This directly satisfies the need to decrement stock and add a timestamp in one operation.

Exam trap

The trap here is assuming that $set can perform arithmetic like stock - 1, or that replaceOne is suitable for partial updates.

14
MCQeasy

Which method is the safest way to delete a single document from a collection based on a unique identifier?

A.db.collection.remove(filter)
B.db.collection.deleteOne(filter)
C.db.collection.deleteMany(filter)
D.db.collection.drop()
AnswerB

deleteOne is the current standard method for deleting exactly one document. By ensuring that only the first matching document is removed, it minimizes the risk of accidental bulk deletions, which is a critical safety feature when working with production data where mistakes could be irreversible.

Why this answer

The deleteOne method is the safest way to remove a single document because it accepts a filter and stops after deleting the first matching document, even if multiple documents match. This prevents accidental data loss that could occur with deleteMany if the filter criteria were not sufficiently specific. It is a fundamental practice to use the most restrictive method possible for destructive operations.

Exam trap

Test-takers frequently confuse deleteOne with remove methods or assume drop() safely targets a single specific document using a unique identifier filter.

15
Multi-Selecthard

Which THREE of the following are valid MongoDB CRUD query operators?

Select 3 answers
A.$gt
B.$ne
C.$and_not
D.$exists
E.$is_null
AnswersA, B, D

$gt is a comparison operator that selects documents where the value of a field is greater than a specified value. It is essential for range queries, such as finding products with prices above a certain threshold or retrieving records created after a specific timestamp.

Why this answer

MongoDB provides a rich set of query operators for filtering and modifying data. Operators like $gt, $ne, and $exists are staples of the query language. Mastering these allows developers to construct complex, powerful queries to extract specific data subsets.

Understanding the syntax and behavior of these operators is a key requirement for the C100DBA certification and effective day-to-day database administration work.

Exam trap

Candidates frequently include non-existent or update-only operators like $set or $update in the list of valid query operators, failing to distinguish between filtering and modification syntax.

16
MCQmedium

Which method is the most efficient way to perform a bulk update of multiple documents in a single request?

A.db.collection.updateMany() inside a for loop
B.db.collection.bulkWrite()
C.db.collection.update()
D.db.collection.saveMany()
AnswerB

The bulkWrite method is specifically designed for batching multiple write operations into a single network request. It provides better performance and reduces the overhead associated with individual commands. This is the recommended approach for any application requiring high-volume data modifications or massive import operations.

Why this answer

The bulkWrite method provides a way to perform multiple write operations (insert, update, delete) in a single request to the server. This reduces network round-trip latency significantly compared to executing individual update operations in a loop. It is the best practice for high-performance data processing tasks where many small updates need to be applied to the database, ensuring optimal throughput and lower overhead.

Exam trap

Candidates often suggest using a loop with individual updateOne() calls, failing to realize that this results in excessive network round-trips that significantly degrade performance compared to bulk operations.

17
MCQmedium

A developer needs to retrieve a subset of fields from a collection. Which TWO methods achieve this using projection?

A.db.collection.find(query, projection)
B.db.collection.findOne(query, projection)
C.db.collection.aggregate(pipeline, projection)
D.db.collection.findAndModify(query, projection)
E.db.collection.update(query, projection)
AnswerA, B

The find method accepts a second argument for projection. This defines which fields to include or exclude from the returned cursor. It is the standard way to retrieve a subset of fields from multiple documents in a collection while maintaining high performance for large datasets.

Why this answer

Projection allows developers to minimize network bandwidth and memory usage by returning only necessary fields from documents. Both find() and findOne() support a second argument that defines the projection document. This is a fundamental optimization technique in MongoDB to prevent the 'select *' anti-pattern, ensuring that large fields like binary data or embedded arrays are not fetched when they are not required by the application layer.

Exam trap

Candidates often choose incorrect method names or assume projection works as a standalone command rather than a secondary argument passed to standard query methods.

18
MCQmedium

What is the result of applying a $push operator with a value of [1, 2] to an existing array field [0]?

A.[0, 1, 2]
B.[0, [1, 2]]
C.[1, 2]
D.Error
AnswerB

The $push operator adds the entire input object as a single new element. Since the input is an array [1, 2], the resulting array contains the original elements plus the new nested array at the end. This is standard behavior for $push when adding complex objects.

Why this answer

The $push operator adds the specified value to the end of the array. If the value itself is an array, $push adds that array as a single element, resulting in a nested structure. If the goal was to append individual elements, the $each modifier should be used with $push.

This distinction is critical for developers managing arrays to ensure the resulting data shape matches the application's expected schema.

Exam trap

Developers often assume the $push operator automatically flattens arrays, mistakenly expecting [0] plus [1, 2] to result in [0, 1, 2] instead of a nested array structure.

19
MCQmedium

You are a MongoDB DBA at a retail company. The 'orders' collection has a document with _id: 100 and status: 'pending'. You need to atomically update the status to 'shipped' only if the current status is 'pending'. Which update operation should you use?

A.db.orders.replaceOne({_id: 100}, {status: 'shipped'})
B.db.orders.updateOne({_id: 100, status: 'pending'}, {$set: {status: 'shipped'}})
C.db.orders.updateOne({_id: 100}, {$set: {status: 'shipped'}})
D.db.orders.findAndModify({query: {_id: 100}, update: {$set: {status: 'shipped'}}})
AnswerB

Including status: 'pending' in the query filter ensures the update only occurs if the document currently has that status. MongoDB's updateOne is atomic at the document level, so the check and update happen as a single operation, preventing race conditions where another process might change the status between a separate read and write.

Why this answer

The correct approach is to include the current status in the query filter so the update only applies when the status is 'pending'. This leverages MongoDB's atomic single-document updates, ensuring the condition and modification occur as one indivisible operation. Using a filter without the status condition would update regardless of the current value, risking data integrity.

Exam trap

The trap here is assuming that any updateOne with a filter on _id is sufficient, but the filter must also include the condition on the field being changed to enforce conditional update.

20
MCQmedium

Refer to the exhibit. Which documents will this query return?

A.All documents with 'electronics' tag sorted by price ascending.
B.The 5 cheapest products tagged 'electronics' that cost less than 500.
C.Any 5 products with price less than 500, regardless of tags.
D.The 5 most expensive products tagged 'electronics' that cost less than 500.
AnswerB

The query correctly filters by the tag and price range, sorts by price in ascending order to find the cheapest items, and restricts the output to the top five results. This accurately describes the logic executed by the MongoDB query engine based on the provided find, sort, and limit.

Why this answer

This query retrieves documents containing 'electronics' in the 'tags' array where the price is less than 500. The results are ordered by price in ascending order, and only the first 5 documents are returned. This combination demonstrates how to perform complex filtering, sorting, and limiting, which is fundamental for building performant search and discovery features in MongoDB-backed applications.

Exam trap

Candidates often overlook the order of operations, forgetting that sorting and limiting happen after the filter is applied. They may guess the order incorrectly when multiple modifiers are present.

21
MCQeasy

You are a MongoDB DBA and need to retrieve all documents from the 'products' collection where the 'price' field is greater than 100 and the 'category' is 'electronics'. Which query accomplishes this?

A.db.products.find({price: {$gt: 100}, category: 'electronics'})
B.db.products.find({$or: [{price: {$gt: 100}}, {category: 'electronics'}]})
C.db.products.find({price: {$gt: 100}}).filter({category: 'electronics'})
D.db.products.find({$and: [{price: {$gt: 100}}, {category: 'electronics'}]})
AnswerA

This query uses an implicit AND by specifying multiple field conditions in the query document. It matches documents where price is greater than 100 and category equals 'electronics'. This is the standard and most efficient way to combine conditions in MongoDB, as it uses the query optimizer effectively.

Why this answer

The implicit AND by combining field conditions in a single query document is the standard way to match documents where multiple criteria must be true. Using $and explicitly is also valid but redundant. $or would match either condition, and .filter() is not a MongoDB method.

Exam trap

The trap here is overcomplicating with $and when implicit AND suffices, or mistakenly using $or when both conditions are required.

22
MCQmedium

Which query operator matches documents where a field contains a value greater than or equal to a specified value?

A.$gt
B.$ge
C.$gte
D.$eq
AnswerC

The $gte operator is the standard comparison operator for matching values greater than or equal to a specified limit. It is inclusive of the value provided. This is the correct tool for standard range queries where the boundary value should be included in the returned result set.

Why this answer

The $gte operator (greater than or equal to) is a comparison operator used in query filters. It is essential for range-based queries, such as filtering for dates after a specific threshold, product prices above a minimum, or version numbers. Understanding these comparison operators is fundamental to building expressive and efficient queries that narrow down result sets effectively within the MongoDB document model.

Exam trap

Candidates frequently mix up comparison operators like $gte with $gt, or misremember the exact syntax of the operator token name.

23
MCQmedium

Which operator is used to perform a logical OR operation across multiple query conditions?

A.$and
B.$not
C.$or
D.$nor
AnswerC

$or is the standard operator for logical disjunction. It accepts an array of expressions and returns documents that match any of the provided conditions. This is the correct choice for scenarios where a query needs to satisfy a variety of possibilities within the document model.

Why this answer

The $or operator enables the evaluation of multiple conditions, returning documents that satisfy at least one of them. It is essential for complex filtering where data might fall into different categories. By nesting conditions within an $or array, developers can perform sophisticated queries that are not possible with simple key-value pairs, allowing for flexible data retrieval patterns in diverse application environments.

Exam trap

Candidates sometimes confuse the $or operator with the $in operator. While both handle multiple conditions, $or is for distinct fields or complex expressions, whereas $in is for multiple values of a single field.

24
MCQeasy

What is the primary function of the 'projection' parameter in the find() method?

A.To filter which documents are returned.
B.To specify which fields to return in the documents.
C.To sort the returned documents.
D.To limit the number of documents returned.
AnswerB

The projection defines the shape of the returned document by including or excluding specific fields. It is a critical performance tool because transferring unnecessary data from the database to the application increases latency and memory usage, especially when dealing with large collections or documents with many fields.

Why this answer

Projections allow you to limit the data returned by a query, which is a best practice for reducing network traffic and memory consumption on both the client and the server. By requesting only the fields required for the current task, you optimize application performance and security. This is a foundational concept in database interaction that helps maintain efficient data flow in large-scale applications.

Exam trap

Candidates frequently confuse the projection parameter with the query filter parameter, attempting to use projection to limit the number of documents returned instead of just the fields within those documents.

25
MCQhard

A sharded cluster stores customer documents in the customers collection, sharded on the customerId field. An application runs an updateOne with the filter { email: "user@example.com" } and the update { $set: { tier: "gold" } }. The email field is not the shard key and has no index. What is the most likely outcome of this operation?

A.The update is routed only to the shard that owns the email range because mongos maintains a global index on email.
B.The update fails immediately because the filter does not include the shard key.
C.The mongos broadcasts the update to all shards, and each shard performs a collection scan to evaluate the filter.
D.The update succeeds only on the primary shard and is silently ignored on other shards.
AnswerC

Without the shard key in the filter, mongos cannot target a specific shard, so it sends the update to every shard. On each shard, the email field has no index, so the shard must scan documents to find matches. This is the expected, if inefficient, behavior for a non-shard-key, unindexed filter in a sharded collection.

Why this answer

In a sharded collection, routing decisions depend on the shard key. Because the filter uses email, which is neither the shard key nor indexed, mongos cannot target a shard and must broadcast to all shards. Each shard then scans its local documents to evaluate the filter, making the update a scatter-gather operation.

The update is not rejected, and no global email index exists.

Exam trap

The trap here is assuming that a sharded cluster automatically indexes or routes on any filter field, when routing is determined by the shard key.

26
MCQhard

A DBA is investigating a performance issue. A query on the `logs` collection uses the following filter: `{ $or: [ { level: "error" }, { level: "warning" } ] }`. There is an index on `{ level: 1 }`. Which statement correctly describes how MongoDB executes this query?

A.MongoDB will use the index on `level` to perform two separate index scans and then merge the results.
B.MongoDB will use the index only if the `$or` clauses are combined with `$and`.
C.MongoDB will perform a collection scan because `$or` queries cannot use indexes.
D.MongoDB will use the index on `level` but only for the first clause in the `$or` array.
AnswerA

For `$or` queries, MongoDB can use an index for each clause if the clauses are supported by indexes. Here, both clauses are equality matches on `level`, which the index supports. MongoDB will execute two index scans and combine the results, often using a merge sort or deduplication step.

Why this answer

For `$or` queries where each clause can be satisfied by an index, MongoDB performs separate index scans for each clause and then merges the results. This is more efficient than a collection scan. The index on `level` is suitable for both equality conditions, so the query will leverage it twice.

Exam trap

The trap here is assuming that `$or` queries cannot use indexes or that only the first clause benefits from an index.

27
MCQmedium

Which cursor method should you use to sort documents by a field named 'age' in descending order?

A..sort({age: 1})
B..sort({age: -1})
C..orderBy({age: 'desc'})
D..order({age: 'desc'})
AnswerB

In MongoDB, -1 represents descending order and 1 represents ascending order. {age: -1} correctly sorts the documents by the 'age' field from highest to lowest. This is the correct way to retrieve documents in reverse chronological or numerical order based on any chosen field.

Why this answer

The sort() method is used to define the order of results returned by a query. Passing {age: -1} ensures that the documents are ordered from oldest to youngest. Mastering sorting is essential for returning data in a meaningful way to users, such as showing the most recent posts or the highest-rated products first, which are common requirements for almost all web and mobile applications.

Exam trap

Students frequently confuse the syntax for ascending (1) and descending (-1) order, or attempt to use keywords like 'DESC' which are not part of the MongoDB shell syntax.

28
MCQmedium

A MongoDB 6.0 replica set has a collection called orders with the default read concern. Users occasionally see an order document that still shows status "pending" even though a separate application thread just updated it to "shipped" and received an acknowledgment. The update used default write concern and targeted a single document by _id. Which read concern should you set on the read operation to guarantee the read returns data acknowledged by a majority of replica set members?

A.readConcern: "snapshot"
B.readConcern: "available"
C.readConcern: "local"
D.readConcern: "majority"
AnswerD

Majority read concern returns only data that has been acknowledged by a majority of replica set members. Once the update thread receives default acknowledgment, a subsequent majority read is guaranteed to see the committed "shipped" state, eliminating the stale "pending" observation. This is exactly the guarantee needed for the described symptom.

Why this answer

The symptom is a stale read after an acknowledged single-document update in a replica set. Majority read concern ensures the read only returns data that a majority of members have acknowledged, so the newly committed "shipped" status becomes visible. Local and available provide no such guarantee, and snapshot is aimed at multi-document consistency rather than this single-document visibility problem.

Exam trap

The trap here is assuming that a default acknowledged write immediately becomes visible to all reads, when in fact only majority read concern guarantees that majority-acknowledged data is returned.

29
MCQmedium

Which update operator would you use to increase the value of a numeric field by a specific amount?

A.$add
B.$inc
C.$set
D.$mul
AnswerB

The $inc operator atomically increments a field by the specified amount. It supports both positive and negative values for incrementing and decrementing, respectively. This is the correct choice for managing counters, such as page views or inventory levels, where accuracy under high concurrency is a strict requirement.

Why this answer

The $inc operator is the standard tool for atomic numeric increments. It is highly efficient because it allows the database to perform the math on the server side without requiring the client to read the current value, perform the addition locally, and write it back. This eliminates race conditions where two clients might read the same value and overwrite each other's increments.

Exam trap

Candidates often mistakenly use the $set operator with arithmetic expressions to update numeric fields, completely ignoring the atomic server-side increment capabilities provided by the $inc operator.

30
MCQeasy

You need to remove a single document from the `users` collection where the `email` field is "alice@example.com". The collection has a unique index on `email`. Which method should you use?

A.db.users.deleteOne({ email: "alice@example.com" })
B.db.users.drop({ email: "alice@example.com" })
C.db.users.deleteMany({ email: "alice@example.com" })
D.db.users.remove({ email: "alice@example.com" })
AnswerA

deleteOne removes the first document that matches the filter. Since email is unique, there is at most one matching document, so deleteOne is appropriate and efficient. It returns a DeleteResult with the number of documents deleted, allowing confirmation that exactly one document was removed.

Why this answer

deleteOne is the correct method to remove a single document matching a filter. It is the modern replacement for remove() and is designed for deleting one document. Since the email field has a unique index, there is at most one match, making deleteOne both safe and efficient. deleteMany and drop are inappropriate because they either delete multiple documents or the entire collection.

Exam trap

The trap here is using deleteMany when only one document should be deleted, or using the deprecated remove() method.

31
MCQmedium

Which method should you use to update multiple documents in a collection and insert a new document if no matches are found?

A.db.collection.updateOne()
B.db.collection.replaceOne()
C.db.collection.updateMany({filter}, {update}, {upsert: true})
D.db.collection.save()
AnswerC

This is the correct command structure for updating multiple documents while enabling the upsert feature. By setting the third parameter object with upsert true, MongoDB will apply the update to all matching documents or create a new document based on the query and update data if no matches exist.

Why this answer

The updateMany method modifies all documents matching the filter. When combined with the 'upsert' option set to true, it ensures that if no documents match the query criteria, a single new document is created containing the filter and update criteria. This pattern is critical for idempotent data ingestion pipelines where you must guarantee existence of records without performing separate check-then-insert logic, thus preventing race conditions.

Exam trap

Candidates often confuse updateMany with updateOne or forget that the upsert option must be explicitly set to true, otherwise no new document will be inserted if zero matches are found.

32
MCQeasy

When performing a findOne operation, what does MongoDB return if no document matches the query criteria?

A.An empty document ({})
B.null
C.An error code
D.An empty cursor
AnswerB

In MongoDB, findOne returns the matching document if found, or null if no document satisfies the query. This is the expected behavior and allows developers to easily check the existence of a record using standard conditional logic within their application code, preventing common errors.

Why this answer

The findOne method is designed to return a single document or null. Returning null is the standard way for the driver and shell to indicate that the search criteria did not produce a match. This is important for application control flow, as developers must always verify that a document was actually retrieved before attempting to access its fields to avoid null pointer exceptions in their code.

Exam trap

Candidates often assume that findOne will throw an error if no document is found, leading to improper error handling in their code instead of checking for a null result.

33
MCQmedium

Which operator would you use to remove an element from an array field in a document?

A.$remove
B.$pop
C.$pull
D.$unset
AnswerC

$pull is the correct operator to remove all elements from an array that match a specific condition. It is efficient and atomic, allowing for precise modification of array fields without the need to read the full document state into the application, which is crucial for high-concurrency systems.

Why this answer

The $pull operator is the primary tool for removing items from arrays based on a specified query condition. It is highly effective because it allows you to remove one or many matching elements in a single operation without needing to pull the entire document into application memory, modify the array, and push it back. This promotes efficient resource usage and data consistency.

Exam trap

Candidates often confuse $pull with $pop, assuming $pop can remove elements by matching specific values or conditions rather than just by index position.

Ready to test yourself?

Try a timed practice session using only CRUD Operations questions.