Courseiva

MongoDB Certified DBA Associate (C100DBA) — Questions 1–75

222 questions total · 3pages · All types, answers revealed

Page 1 of 3

Page 2
1
MCQmedium

An application uses a compound index on `{ 'status': 1, 'priority': -1 }`. Which query will efficiently use this index?

A.db.tasks.find({ 'priority': 5 })
B.db.tasks.find({ 'status': 'open' })
C.db.tasks.find({ 'created': '2023-01-01' })
D.db.tasks.find({ 'status': 'open', 'type': 'urgent' })
AnswerB

Since the query filters by the leading field in the compound index ('status'), it can perform an index scan. This allows the database to quickly narrow down the result set without scanning every document in the collection, leading to significantly better performance for the application's read operations.

Why this answer

Compound indexes are ordered. A query will only use the index if the query filter matches the prefix of the indexed fields. Here, the index starts with 'status'.

Therefore, queries filtering on 'status' and optionally 'priority' will be efficient. Understanding index prefixing is crucial for DBAs to ensure that developers write efficient queries that fully leverage the index structures, avoiding unnecessary collection scans and keeping performance stable as the data grows.

Exam trap

Candidates often think an index on fields B and C can be used when querying only field C, ignoring the strict left-to-right prefix rule of compound indexes.

2
MCQmedium

What is the primary benefit of using a Covered Query in MongoDB?

A.It forces the data to stay in the WiredTiger cache.
B.It avoids reading the full document from disk.
C.It automatically compresses all returned data.
D.It eliminates the need for any index on the collection.
AnswerB

When an index contains all fields required by a query, MongoDB returns the data directly from the index. This removes the need to perform a costly disk fetch to retrieve the full document, significantly reducing I/O operations and improving the overall latency and throughput of the query.

Why this answer

A covered query is one where all the fields in the query projection exist within the index itself. Because the database can retrieve all necessary data directly from the index tree without needing to fetch the actual document from disk, it drastically reduces I/O. This is one of the most effective ways to optimize read performance for high-frequency queries in large collections.

Exam trap

Candidates often confuse covered queries with regular index scans, mistakenly believing that any query using an index avoids disk reads. However, fetching documents that are projected outside the index still requires reading from disk.

3
MCQhard

Refer to the exhibit. What is the primary cause of the performance issue seen in this query plan?

A.The query is hitting the primary index limit.
B.The query requires a full collection scan.
C.The query is being blocked by a write lock.
D.The database is out of memory.
AnswerB

The presence of 'COLLSCAN' in the execution statistics proves that the query engine is reading every document in the collection to find a match. This is the most expensive operation in MongoDB and confirms that the current query filters do not have an associated index to speed up retrieval.

Why this answer

The exhibit shows a 'COLLSCAN', which indicates the database is scanning every document in the collection to satisfy the query. With 500,000 scanned documents returned for a single result, the query is severely inefficient. This demonstrates a lack of a supporting index, leading to high CPU and I/O usage.

Identifying these inefficient queries is vital for DBAs to prevent application-wide slowdowns caused by resource exhaustion on the primary database node.

Exam trap

Candidates frequently misinterpret 'COLLSCAN' as a network latency issue rather than recognizing it as a fundamental lack of an appropriate index for the query filter.

4
MCQmedium

A collection has a 'status' field with only three possible values: 'active', 'pending', and 'closed'. Why is 'status' a poor choice for a shard key by itself?

A.The field is not a unique identifier for the documents.
B.Low cardinality prevents the creation of many chunks.
C.The field type must be an ObjectID for performance reasons.
D.The balancer cannot migrate chunks based on string values.
AnswerB

With only three possible values, MongoDB can only create a very limited number of chunks. Even in a cluster with ten shards, only three shards would ever hold data for this collection, while the others remain empty. This effectively caps the horizontal scalability of the database to three nodes.

Why this answer

A good shard key needs high cardinality to allow for a large number of chunks. If a shard key only has three possible values, the cluster can have at most three chunks for that collection. This limits the total number of shards that can participate in storing and processing the data, leading to scalability bottlenecks and imbalance.

Exam trap

Candidates often incorrectly assume that low cardinality is beneficial because it simplifies query routing, failing to realize that it prevents the cluster from splitting data into many chunks.

5
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.

6
Multi-Selecthard

A financial services company runs a sharded MongoDB cluster with three shards. They need to shard a new collection that stores transaction records. The collection will be queried primarily by 'accountId' and 'transactionDate'. The team wants to minimize scatter-gather queries and ensure even data distribution. Which two actions should they take when choosing and implementing the shard key? (Choose two.)

Select 2 answers
A.Ensure the shard key has high cardinality and low frequency to avoid jumbo chunks and hot spots.
B.Use a compound shard key with 'accountId' as the first field and 'transactionDate' as the second field to support queries that include both fields.
C.Choose a shard key that is monotonically increasing, such as an auto-incrementing transaction ID, to simplify range queries.
D.Use a random shard key generated by the application to guarantee even distribution across shards.
E.Use a hashed shard key on 'accountId' to ensure even distribution, even though it prevents efficient range queries on 'transactionDate'.
AnswersA, B

High cardinality ensures many distinct shard key values, and low frequency means no single value dominates. This prevents large, unsplittable chunks (jumbo chunks) and uneven write distribution. For transaction records, 'accountId' combined with 'transactionDate' can provide high cardinality and low frequency if accounts are numerous and transactions are spread over time.

Why this answer

The compound shard key with 'accountId' first supports targeted queries on account and range queries on date, while also providing high cardinality and low frequency. This combination reduces scatter-gather and avoids hot spots. Hashed or random keys improve distribution but break query targeting, and a monotonically increasing key creates write hot spots.

Exam trap

The trap here is focusing only on even distribution and ignoring query patterns, leading to choices that cause scatter-gather.

7
MCQmedium

An organization wants to restrict customer data for European Union residents to a specific set of physical servers located in Frankfurt, complying with data residency regulations. Which MongoDB sharding feature should the DBA implement to achieve this?

A.Zone sharding, which associates specific shard key ranges with designated groups of shards to enforce data residency rules.
B.Dynamic range compression, which encrypts and confines specific database collections to localized storage volumes on individual nodes.
C.Global cluster replication, which synchronizes all database documents simultaneously across every shard in every continent.
D.Read preference tagging, which routes read operations to secondary members in specific data centers without altering write locations.
AnswerA

Zone sharding, which associates specific shard key ranges with designated groups of shards to enforce data residency rules. Zone sharding enables administrators to map document ranges to specific physical shards, ensuring data partitions remain confined to designated geographical locations.

Why this answer

Zone sharding allows administrators to associate specific shard key ranges with defined sets of shards called zones. By tagging European servers into an 'EU' zone and associating the region shard key range with that zone, MongoDB guarantees that EU customer data stays exclusively on those designated physical shards. This is critical for regulatory compliance and data sovereignty requirements.

Exam trap

Candidates confuse standard sharding with zone sharding, failing to realize that zone tags are strictly required to restrict data to specific physical servers for compliance.

8
MCQeasy

A MongoDB DBA is configuring a new sharded cluster. The application requires that queries on the sharded collection include the shard key to avoid scatter-gather. The DBA decides to use a ranged shard key on the field 'region'. After sharding, the DBA notices that queries filtering only on 'region' are performing well, but queries that also filter on 'city' are still scanning all shards. What is the most likely cause?

A.The 'city' field is not indexed, causing the query to scan all shards.
B.The shard key does not include 'city', so queries with both 'region' and 'city' cannot be targeted to a single shard.
C.The balancer has not yet distributed chunks evenly, so some shards have more data and cause the query to scan them.
D.The shard key 'region' has low cardinality, so queries cannot be targeted efficiently.
AnswerB

In a sharded cluster, only queries that include the shard key can be routed to specific shards. Since the shard key is only 'region', a query with both 'region' and 'city' still only uses 'region' for targeting. The 'city' filter is applied after routing, so the query may still target multiple shards if the region spans them, but it is not scatter-gather across all shards solely due to 'city'.

Why this answer

Query targeting in a sharded cluster depends on the shard key. If the shard key is only 'region', queries that filter on 'region' can be routed to specific shards. Adding 'city' does not change the routing because 'city' is not part of the shard key.

To target on both fields, the shard key would need to be compound, including both 'region' and 'city'.

Exam trap

The trap here is assuming that any indexed field can be used for shard targeting, when only the shard key determines routing.

9
MCQmedium

How does the 'w: majority' write concern align with the philosophy of data reliability in MongoDB?

A.It guarantees that the write is applied to all shards.
B.It ensures the data is durable on a majority of nodes.
C.It optimizes for the fastest possible write performance.
D.It forces an immediate sync to the storage disk.
AnswerB

By requiring acknowledgment from a majority of the replica set nodes, MongoDB provides a high degree of confidence that the data is not lost if the primary fails. This aligns with the philosophy of balancing write performance with data safety and persistence.

Why this answer

The 'w: majority' write concern ensures that a write operation is acknowledged only after it has been replicated to a majority of nodes in the replica set. This philosophy prioritizes data durability and consistency over the absolute lowest latency. By requiring a majority, MongoDB ensures that even if a primary node fails immediately after a write, the data persists on other nodes, minimizing the window for data loss during failover.

Exam trap

Many candidates mistakenly believe 'w: majority' ensures the data is written to all nodes in the cluster, confusing it with absolute synchronization rather than a majority quorum of voting members.

10
MCQmedium

What happens to the replica set if a majority of voting members are permanently lost?

A.The set automatically switches to a single-node mode to remain functional.
B.The set stops accepting writes to maintain consistency.
C.The secondary nodes elect a new primary regardless of the missing majority.
D.The primary node continues to accept writes for a short period.
AnswerB

Without a majority, the remaining nodes cannot achieve consensus for write operations. To prevent split-brain and maintain consistent data, the replica set stops accepting writes. This ensures that no data is committed until the cluster can confirm that a quorum of nodes has successfully processed the operation.

Why this answer

A replica set requires a majority of its voting members to be online to elect a new primary and perform write operations with majority concern. If the majority is lost, the remaining nodes enter a read-only state, as they cannot reach consensus. This is a critical failure scenario that requires immediate administrative intervention, such as reconfiguring the set or restoring the failed nodes.

Exam trap

Candidates incorrectly assume the replica set remains fully functional as long as one node is alive, ignoring the requirement for a majority to maintain cluster consistency.

11
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.

12
MCQmedium

A production MongoDB 6.0 sharded cluster has a collection with a ranged shard key on the field `customerId`. Over time, the team notices that nearly all new documents have monotonically increasing `customerId` values, and one shard is receiving a disproportionate share of writes while the other shards remain relatively idle. The balancer is enabled and running. Which of the following is the most likely explanation for this imbalance?

A.The shard key is monotonically increasing, causing all new inserts to target the highest chunk on a single shard.
B.The shard key field is not indexed on the shards, forcing all writes to a single primary.
C.The config servers are overloaded and cannot process chunk migration commands.
D.The collection has too few chunks, so the balancer cannot distribute them evenly across shards.
AnswerA

A monotonically increasing shard key like an incrementing `customerId` means new documents always fall into the highest chunk, which resides on one shard until the balancer migrates it. This creates a hot shard for writes, a well-known anti-pattern for ranged shard keys with sequential values.

Why this answer

With a monotonically increasing shard key, new inserts always target the chunk with the highest key range. Because chunks are assigned to shards, that highest chunk lives on one shard at a time, making it a write hotspot. The balancer will eventually migrate chunks, but the stream of new inserts keeps hitting the newest chunk, so the imbalance persists.

Exam trap

The trap here is assuming the balancer can fully compensate for a poor shard key choice, when in fact a monotonic key will always create a write hotspot regardless of balancing.

13
MCQhard

When using 'readConcern: majority', what is the specific guarantee provided to the client?

A.It guarantees that the read will never return stale data.
B.It guarantees that the data read has been committed to a majority of nodes.
C.It forces the read to always come from the primary node.
D.It increases the speed of queries by ignoring consistency.
AnswerB

This read concern ensures that the returned data is part of the majority-committed history. This means the data is permanent and cannot be rolled back during a future election. It is a fundamental feature for building reliable distributed systems where data integrity must be maintained across node failures.

Why this answer

The 'majority' read concern guarantees that the data returned has been acknowledged by a majority of the replica set members. This ensures that the data is durable and will not be rolled back in the event of a primary failover. It provides a higher level of consistency for read operations, which is critical for applications that require strict data integrity and visibility.

Exam trap

Candidates frequently assume that 'readConcern: majority' guarantees data has been written to all nodes in the replica set rather than just a majority.

14
MCQmedium

A security audit requires that sensitive document data contained in query parameters must not be written to the MongoDB system logs. Which server configuration setting should be enabled?

A.security.authorization: enabled
B.security.redactClientLogData: true
C.operationProfiling.mode: off
D.storage.wiredTiger.collectionConfig.blockCompressor: zlib
AnswerB

Enabling 'redactClientLogData' ensures that the mongod process removes potentially sensitive information from log messages before they are written to disk. This specifically targets the data within commands, such as query filters or document fields, replacing them with placeholders to prevent data leaks through log files.

Why this answer

Security administration involves protecting data at rest, in transit, and in logs. Log redaction is a feature that prevents sensitive information, like the contents of a 'find' filter or an 'insert' document, from appearing in the server logs. This is essential for compliance with regulations like GDPR, HIPAA, or PCI-DSS.

Exam trap

Candidates often confuse log redaction configuration parameters with general verbosity settings or audit filters, failing to recall the exact setting name.

15
MCQhard

Refer to the exhibit. An aggregation pipeline is failing with an error. How can you modify the pipeline to allow it to process the large dataset?

A.Set 'allowDiskUse' to true in the aggregation options.
B.Increase the RAM allocated to the mongod process configuration.
C.Remove the $group stage and perform the grouping in application code.
D.Reduce the batch size in the cursor options.
AnswerA

The allowDiskUse option explicitly authorizes the aggregation pipeline to write temporary data to the _tmp directory on the server disk when the memory limit is reached. This enables processing of datasets that exceed 100MB of RAM, effectively resolving the memory limit error.

Why this answer

The error indicates that the group operation is exceeding the 100MB RAM limit. By setting 'allowDiskUse: true', you permit the MongoDB server to use temporary files for the aggregation process. This is a common requirement for complex analytics where the data working set is larger than the available RAM, ensuring that long-running operations can complete successfully without crashing due to memory exhaustion.

Exam trap

Students often try to solve memory limit aggregation errors by scaling up server RAM instead of using the native pipeline configuration option meant for temporary storage.

16
MCQhard

What occurs when a replica set member experiences a 'rollback'?

A.The node automatically merges its divergent data with the primary.
B.The node is permanently removed from the replica set until manually re-added.
C.The node discards data to align with the new primary and saves it to rollback files.
D.The node initiates a global election to force a return to its old state.
AnswerC

During a rollback, the node reverts its local state to the point of divergence from the current primary. The discarded operations are written to separate BSON files on the local filesystem. This process ensures the cluster returns to a consistent state while preserving the orphaned data for forensic analysis.

Why this answer

Rollback happens when a node was previously a primary, performed writes that were never replicated to the majority, and then rejoined the set after a new primary was elected. To maintain consistency, the old primary must discard those unacknowledged writes to match the new primary's state. These discarded writes are saved to a local BSON file for manual inspection and potential recovery by administrators.

Exam trap

Candidates frequently mistake rollback for a simple 'undo' operation or a database crash recovery, failing to realize it involves moving data to local files for manual administrator intervention.

17
MCQmedium

Which command is used to check the current replication lag status on a secondary node?

A.rs.status()
B.rs.printReplicationInfo()
C.rs.printSecondaryReplicationInfo()
D.db.stats()
AnswerC

This specific shell helper calculates the difference between the primary's last operation and the secondary's applied operation, outputting the lag in seconds. It is the most effective command for quickly identifying which nodes are falling behind and verifying that the entire set is effectively synchronized.

Why this answer

The rs.printSecondaryReplicationInfo() command provides a convenient summary of how far behind each secondary is compared to the primary. This is a vital tool for monitoring the health of the replica set and identifying nodes that may be having trouble keeping up with the write volume, which could signal underlying network or hardware performance bottlenecks.

Exam trap

Candidates often confuse this command with rs.status(), which provides general replica set health but requires manual calculation to determine the actual replication lag duration for secondaries.

18
MCQmedium

Refer to the exhibit. What does this output indicate about the query performance?

A.The query is fully covered by an index.
B.The query requires an index to avoid a full collection scan.
C.The query is performing well because nReturned equals totalDocsExamined.
D.The index is being used, but it is not selective enough.
AnswerB

The presence of COLLSCAN signifies that no suitable index was found to narrow the search scope. To improve performance, an index should be created on the fields used in the query filter, which would allow the database to locate the necessary documents using an efficient index scan instead.

Why this answer

A 'COLLSCAN' indicates that the database is performing a full collection scan, reading every document to satisfy the query. The high number of docs examined relative to the returned documents suggests that the query is inefficient. In a production environment, this is a major performance bottleneck, as the database engine must load entire documents into memory to evaluate the filter, leading to high I/O and latency.

Exam trap

Candidates often confuse IXSCAN with COLLSCAN, mistakenly believing that a high number of examined documents in a full scan means the index is working effectively.

19
Multi-Selecthard

A logistics company is designing a MongoDB database for a real-time shipment tracking system. The operations team needs to frequently update shipment statuses and query the latest events. The development team is debating the trade-offs of embedding versus referencing for the shipment events. Which two considerations align with MongoDB's philosophy for this scenario? (Choose two.)

Select 2 answers
A.Embedding events within the shipment document ensures atomic updates and fast reads for the event history.
B.Embedding events is always preferred because it eliminates the need for multi-document transactions.
C.Referencing events requires using $lookup for every read, which is as fast as an embedded document read.
D.Embedding events ensures that the shipment document remains small and efficient for writes.
E.Referencing events in a separate collection allows unlimited growth and avoids the 16 MB document size limit.
AnswersA, E

Embedding events in the shipment document allows the application to retrieve the entire event history with a single query, and updates to the shipment and its events can be atomic within a single document. This aligns with MongoDB's philosophy of storing data that is accessed together. However, it requires monitoring document growth to avoid hitting the 16 MB limit, especially if events are unbounded.

Why this answer

The correct considerations are that embedding provides atomic updates and fast reads for the event history, while referencing allows unlimited growth and avoids the 16 MB limit. These reflect MongoDB's flexible modeling philosophy: choose embedding when data is accessed together and atomicity is needed, but opt for referencing when data grows unbounded or is accessed independently. The decision hinges on access patterns and data lifecycle.

Exam trap

The trap here is thinking that embedding is always better for atomicity, ignoring that unbounded arrays can hit the 16 MB document limit and degrade performance.

20
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.

21
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.

22
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.

23
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.

24
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.

25
MCQeasy

A DBA notices that a query on the products collection uses an index scan but returns only a small fraction of documents. The index is { category: 1, price: 1 }. The query filters on category and price with a range condition on price. Which statement best describes why the index might still be efficient despite scanning many index entries?

A.The index scan is efficient because MongoDB automatically converts it to a collection scan when the selectivity is low.
B.The index scan is efficient because it can use the index bounds to limit the scan to the relevant category and price range, reducing the number of documents fetched.
C.The index scan is efficient because it avoids fetching documents entirely due to the index being covered.
D.The index scan is efficient because it uses the index only for sorting and not for filtering.
AnswerB

When a query filters on category (equality) and price (range), the index { category: 1, price: 1 } allows MongoDB to set index bounds for both fields. It can seek directly to the matching category and then scan only the price range within that category. This limits the number of index entries examined and the number of documents fetched, making the index scan efficient even if it examines many index keys, because it avoids a full collection scan.

Why this answer

The index { category: 1, price: 1 } supports efficient filtering when the query has an equality predicate on category and a range predicate on price. MongoDB can use index bounds to seek to the correct category and scan only the relevant price range, minimizing the number of documents fetched. This makes the index scan efficient despite examining many index entries.

Exam trap

The trap here is assuming that an index scan is inefficient simply because it examines many index keys, when the key benefit is avoiding a full collection scan and fetching only matching documents.

26
MCQmedium

An administrator needs to distribute a high-throughput collection evenly across a sharded cluster using a hashed shard key. What is the primary characteristic of MongoDB's hashed sharding strategy that makes it effective for preventing write bottlenecks?

A.It computes an MD5 hash of the field value to distribute documents pseudo-randomly across all available chunks and shards, preventing single-shard write bottlenecks.
B.It compresses all chunk migration payloads using cryptographic hashing algorithms to minimize network bandwidth consumption during background balancing operations.
C.It automatically converts multi-key array fields into single scalar values to prevent indexing errors on distributed sharded collections.
D.It locks the target shard during write operations to guarantee strict serializable isolation levels across distributed cluster environments.
AnswerA

It computes an MD5 hash of the field value to distribute documents pseudo-randomly across all available chunks and shards, preventing single-shard write bottlenecks. By randomizing the distribution of incoming documents based on their hash values, even sequential identifiers like auto-incrementing integers or timestamps achieve optimal write throughput across the cluster.

Why this answer

Hashed sharding applies an MD5 hash function to the specified field value before routing documents. This transforms sequential or correlated inputs into pseudo-random hash values, ensuring that writes scatter uniformly across all available cluster shards. Understanding hashed sharding mechanisms enables administrators to design resilient write-heavy architectures that prevent the single-shard bottlenecks common with monotonic keys.

Exam trap

Candidates often incorrectly believe that hashed sharding provides faster read performance, confusing the write-distribution benefits of random hashing with query-routing optimization.

27
MCQmedium

A DBA executes 'mongodump --oplog' against a primary node in a replica set. What is the specific purpose of the --oplog flag in this administrative context?

A.It exports the entire oplog collection into a separate BSON file.
B.It captures changes during the dump for point-in-time consistency.
C.It speeds up the dump process by reading from the oplog instead of collections.
D.It automatically compresses the output using the oplog's compression ratio.
AnswerB

The --oplog flag is essential for creating a consistent snapshot of a running database. It ensures that the backup reflects a single point in time by including all writes that occurred between the start and end of the dump, which are then applied during restoration to resolve inconsistencies.

Why this answer

When backing up a live database, data changes while the backup is running. The '--oplog' flag tells mongodump to capture all operations that occur during the dump process. This allows the DBA to restore the database to a consistent state by replaying those operations during the 'mongorestore' process, ensuring data integrity.

Exam trap

Candidates often think --oplog is used for performance or speed, failing to understand its primary purpose is ensuring point-in-time data consistency across the backup.

28
MCQmedium

A sharded cluster has a three-member replica set for its config servers. If two of the three config servers go offline, what is the immediate impact on the cluster's operations?

A.The cluster becomes read-only for all application data.
B.The mongos instances will crash and must be restarted.
C.Chunks cannot be split or migrated between shards.
D.All shards will automatically step down their primary members.
AnswerC

Operations that require updating the cluster metadata, such as chunk splits, migrations, or dropping collections, will fail because the config server replica set lacks a majority to commit writes. The cluster remains operational for standard data access, but its ability to balance or scale is temporarily frozen.

Why this answer

Config servers store the metadata and configuration settings for the entire sharded cluster. They are deployed as a replica set to ensure high availability. If the replica set loses its majority, it can no longer process writes to the metadata, which has significant implications for administrative tasks and the dynamic behavior of the cluster.

Exam trap

Candidates often think losing config server quorum completely stops all read and write operations on existing sharded data.

29
MCQhard

Refer to the exhibit. Which index is most effective for this query?

A.{ tags: 1 }
B.{ tags: 'hashed' }
C.{ tags: 1, _id: 1 }
D.No index is required for array fields.
AnswerA

A multikey index on the 'tags' array allows MongoDB to map each individual element of the array to the document. This enables efficient lookup for specific values like 'red' and 'blue', making it the optimal choice for queries using the $all operator on an array field.

Why this answer

The $all operator is used to find documents where the field contains all the specified elements. When indexing an array field, MongoDB creates a multikey index. A simple index on 'tags' is sufficient here because the multikey index structure inherently supports finding documents that contain specific array elements, enabling the query engine to efficiently narrow down the result set without scanning all documents in the collection.

Exam trap

Exams often tempt candidates to create complex multi-key or compound index variants for array queries when a basic single-field index already natively supports the operation.

30
MCQeasy

Which connection string parameter should be used to ensure an application driver automatically discovers all members of a replica set?

A.maxPoolSize
B.replicaSet
C.wtimeoutMS
D.readPreference
AnswerB

The replicaSet parameter instructs the MongoDB driver to monitor the state of the entire replica set cluster. By providing the replica set name, the driver can verify it is connecting to the correct cluster and discover all hidden, secondary, and primary nodes based on the initial seed list provided.

Why this answer

The replicaSet parameter is essential for drivers to identify the cluster name and initiate the discovery process. When this parameter is specified, the driver uses the provided seed list to perform a 'isMaster' command against the nodes, allowing it to map the entire topology. Understanding this mechanism is vital for ensuring high availability, as the driver needs to dynamically redirect operations to the new primary during automated failover events.

Exam trap

Candidates often select authentication or timeout parameters like 'connectTimeoutMS', wrongly believing they control how a driver discovers cluster topology.

31
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.

32
MCQmedium

An application executes a query on a sharded collection that does not include the shard key. What is the impact on the cluster performance?

A.The query will be rejected by the mongos as an invalid operation.
B.The query will only be sent to the primary shard of the database.
C.The mongos will perform a 'scatter-gather' operation across all shards.
D.The cluster will automatically create a new index to support the query.
AnswerC

In a scatter-gather operation, the mongos sends the query to all shards simultaneously. It then waits for all shards to respond, merges the results, and returns them to the application. This process is expensive in terms of network overhead and CPU usage across the entire cluster.

Why this answer

When a query does not include the shard key, the mongos router cannot determine which shard contains the requested data. As a result, it must broadcast the query to every shard in the cluster. This 'scatter-gather' operation increases resource consumption across all nodes and can lead to significant latency and scalability issues as the cluster grows.

Exam trap

Candidates often confuse a scatter-gather query with a targeted query, mistakenly thinking the mongos router sends the request only to the shard containing the matching range.

33
Multi-Selecthard

Which THREE actions occur when a MongoDB secondary node performs an initial sync?

Select 3 answers
A.It copies all documents from each collection on the primary.
B.It immediately becomes the primary to speed up the process.
C.It applies oplog entries that occurred during the data cloning phase.
D.It builds all indexes defined in the collections.
E.It automatically purges all data from the primary node.
AnswersA, C, D

The first step of initial sync is to copy the data from all databases on the source. The node iterates through each collection and copies all documents. This is necessary to build a baseline state for the new member before it can begin processing the real-time oplog operations from the primary.

Why this answer

During initial sync, the node first clones all databases from the primary, then applies all changes recorded in the oplog that occurred during the cloning phase, and finally builds all necessary indexes for the collections. This multi-stage process ensures the new member reaches a consistent state with the primary without requiring an outage or downtime for the existing cluster members.

Exam trap

Test-takers often assume initial sync copies pre-built indexes directly from the primary, missing the fact that indexes must be built locally.

34
MCQmedium

Which situation is best suited for a Multikey Index?

A.Indexing a collection where every document contains a simple numeric ID.
B.Querying documents based on specific elements inside an array field.
C.Improving the performance of large joins across multiple collections.
D.Enforcing unique constraints on non-array fields.
AnswerB

Multikey indexes are the standard solution for indexing array fields. They allow the database to map each individual array element to the corresponding document, making it possible to query the contents of arrays efficiently. Without a multikey index, querying an array field would result in a slow collection scan.

Why this answer

Multikey indexes are used when you need to index a field that contains an array. MongoDB creates an index entry for each element in the array, allowing you to efficiently query for documents containing specific array values. This is essential for applications managing tags, inventory lists, or user attributes stored as arrays, ensuring that queries filtering by these elements perform with high efficiency rather than scanning the entire collection.

Exam trap

Candidates mistakenly believe Multikey indexes are for general performance optimization, rather than specifically for indexing fields that contain arrays, leading to incorrect index selection for standard field queries.

35
MCQmedium

What is the consequence of having a high number of 'keysExamined' compared to 'nReturned' in a query?

A.The index is too small and needs to be rebuilt.
B.The query is inefficiently scanning the index.
C.The database is performing a cache miss.
D.The query will be automatically optimized.
AnswerB

When keysExamined is significantly higher than nReturned, the query engine is visiting many index entries that don't match the query. This indicates that the index is poorly suited for the query's filter, causing unnecessary index I/O and increasing the time it takes to return the results.

Why this answer

A large discrepancy between 'keysExamined' and 'nReturned' suggests that the index is not very selective or is being used inefficiently. The engine is scanning many index entries that do not match the query criteria, which is a major performance drain. Investigating the selectivity of the index and potentially adding more fields to the compound index can help narrow down the search and improve efficiency.

Exam trap

Candidates often assume that any index usage is efficient, failing to recognize that a high ratio of examined keys to returned documents indicates a poorly selective or unoptimized index.

36
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.

37
MCQhard

When evaluating index performance, what is the impact of a 'partial index'?

A.It forces all documents in the collection to be indexed.
B.It allows for faster writes by indexing fewer documents.
C.It automatically makes all queries return faster.
D.It is only compatible with unique indexes.
AnswerB

Because a partial index only tracks a subset of documents, fewer index updates are required when documents are inserted or modified. This directly improves write throughput, especially in collections where the vast majority of documents do not match the criteria, effectively optimizing both index size and system performance.

Why this answer

Partial indexes allow you to index only a subset of documents that meet a specific filter condition. This reduces index size and the overhead of maintaining the index during writes, as only updates to documents matching the filter trigger an index update. This is highly effective for reducing memory usage when you only need to index documents with specific statuses, such as 'active' or 'pending', rather than the entire collection.

Exam trap

Test-takers frequently confuse partial indexes with sparse indexes, assuming partial indexes only omit null fields rather than applying arbitrary developer-defined filter expressions.

38
MCQmedium

A company is migrating from a monolithic SQL database to MongoDB. They want to maintain high availability. Which feature is most critical to their success?

A.Horizontal sharding of the data.
B.Automatic failover via Replica Sets.
C.The use of the Aggregation Framework.
D.Strict enforcement of ACID transactions.
AnswerB

Replica Sets are the core mechanism for high availability. They provide data redundancy across multiple nodes and use an automated heartbeat and election process to promote a secondary node if the primary goes down, ensuring continuous operation and minimizing downtime for critical enterprise applications.

Why this answer

High availability in MongoDB is primarily achieved through Replica Sets. A replica set consists of multiple nodes that store the same data, providing redundancy and automatic failover. If the primary node becomes unavailable, the replica set automatically elects a new primary, ensuring the application remains accessible.

This architecture is fundamental to MongoDB's design philosophy of providing a resilient system that can withstand infrastructure failures without impacting the client application's availability.

Exam trap

Candidates frequently confuse 'Sharding' (for horizontal scaling) with 'Replica Sets' (for high availability). They mistakenly choose sharding when the primary goal is just maintaining uptime.

39
MCQmedium

A collection 'events' has a compound index { tenantId: 1, createdAt: -1 }. A developer runs db.events.find({ tenantId: "acme", createdAt: { $gte: ISODate("2024-01-01") } }).sort({ createdAt: -1 }).limit(50). The explain output shows the index is used but the query still performs a large in-memory sort. Which action resolves the sort performance issue?

A.Add a sort key to the index: { tenantId: 1, createdAt: -1, _id: 1 }.
B.Ensure the index is { tenantId: 1, createdAt: -1 } and verify the query does not use a collation or type mismatch that prevents index-provided sort.
C.Reverse the compound index to { createdAt: -1, tenantId: 1 }.
D.Create a separate single-field index on createdAt.
AnswerB

The compound index with equality field tenantId first and sort field createdAt second already satisfies the equality, sort, and range pattern, so the sort should be index-provided. A collation difference, a mismatched field type, or a $or/$in shape can silently force a blocking SORT stage, so confirming these conditions is the correct diagnostic step.

Why this answer

A compound index can provide both the equality match and the sort when the equality fields form the prefix and the sort field follows. With { tenantId: 1, createdAt: -1 }, the query's equality on tenantId and sort on createdAt should be served without an in-memory sort. A blocking SORT in explain therefore points to a mismatch such as collation, type, or query shape rather than a missing index.

Exam trap

The trap here is assuming any sort requires a new index, when a correctly ordered compound index already provides the sort and the real cause is a collation or type mismatch.

40
MCQmedium

You are a DBA for a MongoDB replica set. A secondary node has been down for several days and is far behind the primary. The oplog on the primary has wrapped, and the secondary's last oplog entry is no longer present. What must you do to bring the secondary back into sync?

A.Increase the oplog size on the primary to prevent wrapping and then restart the secondary.
B.Restart the secondary with the --resync option to force a full resync.
C.Run rs.syncFrom() on the secondary to point it to a different sync source.
D.Perform a full resync by stopping the secondary, deleting its data files, and restarting it.
AnswerD

When a secondary's oplog is too stale and the primary's oplog has wrapped, the secondary cannot catch up incrementally. The only way to resync is to perform a full resync, which involves stopping the secondary, deleting its data directory (or using rs.resync() in the shell), and restarting it to perform an initial sync from scratch.

Why this answer

If a secondary's last oplog entry is no longer in the primary's oplog, the secondary cannot catch up incrementally. A full resync is required, which means deleting the secondary's data files and restarting it to perform an initial sync. This process copies all data from the primary or another sync source.

Exam trap

The trap here is assuming that changing the sync source or increasing oplog size can recover a secondary whose oplog entries have been overwritten, rather than performing a full resync.

41
MCQhard

Refer to the exhibit. An administrator inspects chunk metadata for a sharded collection using a compound shard key: { region: 1, account_id: 1 }. What does the presence of MinKey and MaxKey signify in this specific chunk range definition?

A.They represent absolute lower and upper bounds for the account_id field within the EMEA region, ensuring all accounts for that region reside in this chunk.
B.They indicate that the chunk is corrupted and requires immediate repair using the validate command on the config server.
C.They specify encryption keys used by the WiredTiger storage engine to secure data chunks at rest on shard01.
D.They are temporary placeholder values assigned by the balancer during active chunk splits that will automatically expire after twenty-four hours.
AnswerA

They represent absolute lower and upper bounds for the account_id field within the EMEA region, ensuring all accounts for that region reside in this chunk. MinKey and MaxKey act as universal wildcards for the trailing compound fields, capturing all possible account identifiers associated with the EMEA region inside shard01.

Why this answer

MinKey and MaxKey represent lower and upper boundary markers in MongoDB that evaluate smaller or larger than any other BSON data type. In this compound chunk range, they ensure that all documents matching the 'EMEA' region regardless of their account_id value fall within this specific chunk. Understanding BSON boundary types is essential for troubleshooting custom chunk splits and zone sharding configurations.

Exam trap

Candidates often misinterpret MinKey and MaxKey as actual data values within the document, rather than understanding them as internal BSON boundary markers used for chunk range definitions.

42
MCQhard

A MongoDB 6.0 sharded cluster has a collection sharded with a hashed shard key on 'userId'. The operations team needs to run an aggregation that groups documents by 'userId' and calculates the total transaction amount. They want to know whether the aggregation can be optimized to run only on the shards that contain the relevant 'userId' values. Which statement describes the correct behavior?

A.The aggregation can target specific shards only if it includes a $sort stage on 'userId' before the $group stage.
B.The aggregation can target specific shards if the $match stage includes an equality condition on 'userId'.
C.The aggregation will always run on all shards because hashed shard keys prevent any query targeting.
D.The aggregation must be run with the allowDiskUse option to target specific shards.
AnswerB

With a hashed shard key, an equality match on the shard key field allows mongos to compute the hash and target the specific shard that owns that hashed value. If the aggregation pipeline begins with a $match on 'userId' with an equality condition, the router can direct the operation to a single shard, avoiding scatter-gather.

Why this answer

For a hashed shard key, mongos can target a specific shard when the query includes an equality condition on the shard key field. This is because the hash of the value determines the chunk and thus the shard. Other stages or options do not affect targeting.

Therefore, an aggregation with a $match on 'userId' with an equality can be optimized to run on a single shard.

Exam trap

The trap here is thinking that hashed shard keys never allow targeting, when equality queries on the hashed field do target a single shard.

43
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.

44
MCQmedium

A media company stores articles with nested comments and tags. The development team wants to retrieve an article along with its comments in a single database round trip. Which MongoDB philosophy supports this design?

A.Using a relational foreign key constraint between articles and comments
B.Embedding related data within a single document
C.Storing comments as a comma-separated string in a single field
D.Normalizing comments into a separate collection with manual joins
AnswerB

Embedding related data within a single document allows the article, its comments, and tags to be stored together. A single query on the article document returns all embedded data, eliminating the need for multiple round trips. This matches MongoDB's document model philosophy of keeping related data together for efficient access.

Why this answer

Embedding related data such as comments and tags within the article document allows the application to retrieve everything in one query. This reduces round trips and latency, directly supporting the team's goal of a single database call to render an article page.

Exam trap

The trap here is assuming that referencing with manual joins is equivalent to embedding, when only embedding guarantees a single-round-trip retrieval.

45
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.

46
MCQmedium

A startup is building a content management system where the document structure varies significantly between blog posts, product pages, and user profiles. Which fundamental MongoDB philosophy best supports this requirement?

A.Normalization ensures data integrity for varying document structures.
B.Strict schema validation enforces identical fields across all documents.
C.Flexible schema design allows documents in the same collection to have different fields.
D.Fixed-length record storage improves indexing speed for variable data.
AnswerC

The document model treats each record as a self-contained unit, meaning fields do not need to be consistent across all documents in a collection. This flexibility empowers developers to iterate quickly, adding new attributes to specific document types without impacting existing records or requiring downtime for database schema changes.

Why this answer

MongoDB’s flexible schema design allows developers to store heterogeneous data types within the same collection. Unlike rigid relational schemas that necessitate complex migrations or NULL-heavy tables for varying attributes, document-oriented storage enables an agile development lifecycle. This philosophy prioritizes developer productivity and adaptability, allowing application code to dictate structure rather than being constrained by predefined table schemas that require frequent and disruptive database-level modifications.

Exam trap

Candidates often assume the solution involves storing data in separate collections, failing to realize that MongoDB's flexible schema is specifically designed to handle heterogeneous data within a single collection.

47
MCQmedium

What is the primary function of the 'wtimeout' setting in write concern?

A.It sets the maximum time a query can run before being killed.
B.It specifies the duration to wait for replica set acknowledgment.
C.It limits the number of write retries in the driver.
D.It defines the connection timeout for new sessions.
AnswerB

wtimeout specifies how long the primary should wait for the required number of replica set members to acknowledge the write operation. If the acknowledgment does not occur within this duration, the primary returns an error to the client, preventing the application from hanging indefinitely during cluster failures.

Why this answer

The 'wtimeout' parameter prevents a write operation from blocking indefinitely if the specified replica set members cannot acknowledge the write. This is a critical safety mechanism for application availability. If a network partition occurs or a node goes offline, the application will receive an error after the timeout, allowing it to handle the failure gracefully instead of hanging the application thread and exhausting the connection pool, which could lead to cascading service outages.

Exam trap

Candidates often believe 'wtimeout' is a performance setting to speed up queries, rather than a safety setting to prevent application threads from hanging indefinitely.

48
MCQmedium

An administrator wants to audit all authentication attempts on a MongoDB Enterprise instance. Which feature should be configured to track these events?

A.Enable 'logLevel' to 5 in the configuration.
B.Set up an 'auditLog' destination in the YAML configuration.
C.Use the 'mongostat' utility.
D.Enable 'net.ssl.mode' to 'requireSSL'.
AnswerB

The 'auditLog' configuration is the designated feature for recording database activities, including authentication successes and failures. By specifying a destination like a file or syslog and defining the filter, administrators can ensure that all relevant security events are recorded in a structured JSON format for easy analysis.

Why this answer

The auditing system in MongoDB Enterprise is essential for compliance and security monitoring. By configuring the audit log to capture events related to authentication and authorization, administrators gain visibility into who is accessing the database and what actions they are performing. This is crucial for forensic analysis, detecting unauthorized access attempts, and satisfying regulatory requirements that mandate detailed record-keeping for all database interactions within a production environment.

Exam trap

Examinees frequently confuse profiling with auditing, incorrectly selecting the database profiler when the question specifically demands tracking security and authentication events.

49
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.

50
Multi-Selectmedium

Which TWO of the following are valid reasons to use an arbiter in a MongoDB replica set?

Select 2 answers
A.To increase the read throughput of the replica set.
B.To break a tie in elections for replica sets with an even number of nodes.
C.To maintain a copy of the data for disaster recovery.
D.To achieve a majority of votes with minimum hardware costs.
E.To act as a hidden node for analytical queries.
AnswersB, D

In an even-numbered replica set, an arbiter provides the necessary third vote to reach a majority during an election. This prevents the cluster from being unable to elect a primary, ensuring that the system remains highly available even if one of the two data-bearing nodes goes offline unexpectedly.

Why this answer

Arbiters are lightweight processes that participate in elections but do not hold data. They are a cost-effective way to achieve a majority for elections in small replica sets. Understanding when to use an arbiter is crucial for designing a cost-efficient and highly available architecture, especially when deploying in multiple zones where adding a full data-bearing node might be cost-prohibitive or unnecessary due to data redundancy requirements.

Exam trap

Candidates incorrectly assume arbiters store a backup copy of the data or improve read performance, misunderstanding their sole purpose of breaking election ties.

51
MCQmedium

Which mechanism ensures an application receives an error if a write is not persisted to the majority of nodes in a replica set?

A.Setting the read concern to 'majority'.
B.Setting the write concern to 'w: majority'.
C.Enabling the 'journal' option on all members.
D.Using the 'majority' read preference.
AnswerB

A write concern of 'w: majority' blocks the application thread until the write is acknowledged by the majority of the replica set members. If the write cannot reach this threshold, the database returns an error to the driver, allowing the application to implement appropriate retry or compensation logic to handle failures.

Why this answer

The 'majority' write concern provides a guarantee that the write operation has been committed to a majority of the replica set members. This is the industry standard for ensuring data durability in the event of a primary node failover. DBAs must enforce this setting for critical business data to prevent 'lost updates' where an application assumes a write is permanent when it actually exists only on the primary that is about to crash.

Exam trap

Students frequently select read preference or journaling parameters, confusing the mechanism for confirming writes across nodes with local disk journaling.

52
Multi-Selectmedium

A DBA is troubleshooting a slow query on a large collection. Which two techniques directly reduce the number of documents the query must examine for an equality-plus-range predicate? (Choose two.)

Select 2 answers
A.Create a compound index with the equality field first and the range field second.
B.Add a hint forcing the query to use the _id index.
C.Create a partial index with a filter expression matching the query's equality predicate.
D.Set the query's read concern to 'majority' to reduce examined documents.
E.Increase the index's fill factor using collMod to leave more space on pages.
AnswersA, C

Placing the equality field first gives the index a tight prefix bound, and the range field second allows the index to scan only the relevant range within that equality. This ordering lets the engine seek directly to matching keys rather than scanning broadly, directly cutting documents examined. It is a core index design rule for mixed equality and range predicates.

Why this answer

Reducing documents examined comes from narrowing the index scan. A compound index ordered equality-then-range lets the engine seek to the exact key range, and a partial index filtered on the equality predicate stores only relevant entries, shrinking the index. Both directly cut keys and documents examined.

Read concern, hint to _id, and page fill settings do not change the access path work for this predicate.

Exam trap

The trap here is treating consistency or storage-tuning knobs like read concern or fill factor as if they reduce the documents a query examines, when only index selectivity and bounds do.

53
MCQeasy

A healthcare startup is evaluating MongoDB for a patient management system. The CTO asks how MongoDB ensures data durability and consistency across multiple servers without manual intervention. Which feature best describes MongoDB's built-in mechanism for automatic failover and data redundancy?

A.Replica sets
B.Write concern
C.Journaling
D.Sharding
AnswerA

Replica sets provide automatic failover and data redundancy by maintaining multiple copies of data across nodes. If the primary node fails, an election automatically promotes a secondary to primary, ensuring continuous availability. This built-in mechanism aligns with MongoDB's philosophy of high availability and durability without manual intervention, making it the correct choice for the scenario.

Why this answer

Replica sets are MongoDB's foundation for high availability, providing automatic failover and data redundancy across multiple nodes. When the primary becomes unavailable, the remaining nodes elect a new primary, allowing the system to continue operating. This built-in mechanism requires no manual intervention and is essential for production deployments that demand continuous uptime and data durability.

Exam trap

The trap here is confusing sharding with replica sets, but sharding is for scaling, not for automatic failover or redundancy.

54
MCQmedium

A development team is building a Node.js application that connects to a MongoDB replica set. They want the driver to automatically retry certain write operations once if they fail due to a transient network error, without requiring custom retry logic in their code. Which connection string option should they enable?

A.w=majority
B.retryWrites=true
C.readPreference=primaryPreferred
D.connectTimeoutMS=30000
AnswerB

Setting retryWrites=true in the connection string enables the driver to automatically retry supported write operations exactly once if they encounter a retryable error, such as a network blip. This meets the team's requirement without custom code and is supported by MongoDB drivers for replica sets and sharded clusters.

Why this answer

The retryWrites=true connection string option instructs the MongoDB driver to automatically retry supported write operations once if they fail with a retryable error. This offloads retry logic from the application code and is the standard way to handle transient network issues in replica sets. Other options affect write concern, read routing, or connection timeouts, but none provide automatic write retries.

Exam trap

The trap here is confusing write concern settings like w=majority with automatic retry behavior; w=majority ensures durability but does not make the driver retry failed writes.

55
MCQhard

What is the consequence of MongoDB's 'write concern' in a distributed environment?

A.It guarantees that all reads are always from the primary.
B.It allows developers to balance latency and durability.
C.It automatically enables sharding across regions.
D.It forces every node to process every write request.
AnswerB

By configuring write concern (e.g., 'w: 1', 'w: majority'), developers explicitly define the trade-off between performance and safety. A 'w: 1' setting is faster but carries a risk of rollback, while 'w: majority' is safer but adds latency due to network round-trips required for replication acknowledgment.

Why this answer

Write concern determines the level of acknowledgment required from the replica set before a write operation is considered successful. A higher write concern ensures stronger data durability by requiring the write to reach a majority of nodes, thereby preventing data loss in the event of a primary failure. This highlights MongoDB's philosophy of allowing developers to choose the right balance between write latency and data safety based on specific application requirements.

Exam trap

Candidates often view write concern only as a speed setting. They fail to understand that it is fundamentally a trade-off between performance latency and data durability guarantees.

56
MCQhard

When is it appropriate to use a hashed shard key instead of a ranged shard key in a MongoDB sharded collection?

A.When the application generates monotonically increasing write keys, and the primary objective is to distribute write operations evenly across all shards to prevent bottlenecks.
B.When the application executes frequent range-based find queries that require contiguous document retrieval across multiple chunks.
C.When the collection dataset size is guaranteed to remain under one gigabyte, eliminating the need for automated chunk balancing.
D.When compliance regulations require all database documents to be encrypted using deterministic hashing algorithms at rest.
AnswerA

When the application generates monotonically increasing write keys, and the primary objective is to distribute write operations evenly across all shards to prevent bottlenecks. Hashing sequential inputs randomizes their distribution, ensuring all shards share the write workload instead of overloading the maximum chunk.

Why this answer

Hashed shard keys are ideal when incoming write operations rely on monotonic or sequential values, such as auto-incrementing IDs or timestamps. Hashing prevents write bottlenecks by scattering insertions across all cluster shards, whereas ranged keys would force all writes onto a single shard.

Exam trap

Candidates often choose ranged shard keys for monotonically increasing fields, creating severe write bottlenecks on a single shard.

57
MCQmedium

An e-commerce application frequently runs a query filtering by category and sorting by price descending. Which index structure provides the optimal performance for this access pattern?

A.{ price: -1, category: 1 }
B.{ category: 1, price: 1 }
C.{ category: 1, price: -1 }
D.{ price: 1, category: -1 }
AnswerC

The category field uses an ascending index prefix for equality matching, while the price field uses a descending direction that matches the requested sort order. This exact alignment allows the query engine to retrieve documents pre-sorted, completely bypassing expensive memory sorting operations.

Why this answer

To optimize queries with equality filters and descending sorts, the index must match the equality field first, followed by the sort field with the correct direction. Placing category first satisfies equality lookup, while setting price to negative one avoids in-memory sorting stages during execution.

Exam trap

Candidates often ignore the sort direction in index creation, assuming that {category: 1, price: 1} will optimize a query that sorts by price in descending order.

58
MCQmedium

A sharded cluster has a collection sharded on `{ location: 1 }`. A query is executed with the filter `{ location: { $in: ["NY", "CA"] } }`. How does MongoDB route this query?

A.The query is sent to all shards because `$in` cannot be targeted.
B.The query is routed to a random shard, and that shard forwards the request to the others as needed.
C.The query is routed to the primary shard for the database because `$in` is not a targeted operation.
D.The query is routed to the shards that own chunks covering the values "NY" and "CA".
AnswerD

When a query includes the shard key with `$in`, mongos can identify the specific chunks that contain those values and route the query only to the shards hosting those chunks. This is a targeted query, which minimizes the number of shards contacted and improves performance.

Why this answer

MongoDB's query router, mongos, can target queries that include the shard key, even with `$in`. It looks up the chunk ranges for the specified values and routes the query only to the shards that own those chunks. This is known as a targeted query and is efficient because it avoids contacting unnecessary shards.

Exam trap

The trap here is assuming that `$in` queries cannot be targeted, when in fact mongos can route them to specific shards based on the shard key values.

59
Multi-Selecthard

You are configuring a MongoDB replica set for a global application. You need to add a member that will never become primary and will be invisible to client applications. Which two steps must you take when adding this member? (Choose two.)

Select 2 answers
A.Set its votes to 0.
B.Set its slaveDelay to a large value.
C.Set its priority to 0.
D.Set its buildIndexes to false.
E.Set its hidden property to true.
AnswersC, E

Setting priority to 0 prevents the member from being elected primary. However, it alone does not make the member invisible to clients. A priority 0 member can still be a sync source and can serve reads if clients connect with appropriate read preferences, unless it is also hidden.

Why this answer

To create a member that never becomes primary and is invisible to clients, you must set both priority to 0 and hidden to true. Priority 0 ensures it cannot be elected primary, while hidden true prevents client visibility and use as a sync source. These two settings together meet the requirements.

Exam trap

The trap here is thinking that setting votes to 0 or slaveDelay is sufficient to make a member non-primary and hidden, when actually hidden and priority 0 are the required settings.

60
MCQeasy

A startup is building a mobile app backend. They want to iterate quickly on features without downtime for schema changes. Which MongoDB characteristic best supports this agile development approach?

A.Schema validation rules that must be updated before any new field can be stored
B.Requiring all documents in a collection to have identical fields at all times
C.The ability to store documents with varying fields without altering a centralized schema
D.Using a fixed-width binary format that cannot represent new data types
AnswerC

MongoDB allows each document to have its own set of fields, so developers can add or change fields without altering a centralized schema or performing migrations. This directly supports rapid iteration and avoids downtime. It is a core philosophical advantage of the document model for agile teams.

Why this answer

MongoDB's document model lets developers add or modify fields per document without a centralized schema migration. This means new features can be deployed without database downtime, directly supporting the startup's need for rapid iteration and continuous delivery.

Exam trap

The trap here is conflating optional schema validation with a mandatory schema, when MongoDB's default flexibility is what enables agile iteration.

61
MCQeasy

A database administrator wants to configure a read preference that directs all read operations to the primary node of a replica set, ensuring the most up-to-date data. Which read preference mode should be used?

A.primaryPreferred
B.primary
C.nearest
D.secondary
AnswerB

The "primary" read preference directs all read operations to the primary node of the replica set. This ensures that the application always reads the most current data, as the primary is the only node that accepts writes. It is the default read preference and is suitable when strong consistency is required.

Why this answer

The requirement is to always read the most up-to-date data, which is only guaranteed when reading from the primary. The "primary" read preference ensures that all reads are directed to the primary node. Other read preferences may read from secondaries, which can have stale data, or may fall back to secondaries if the primary is unavailable, violating the requirement.

Exam trap

The trap here is confusing "primaryPreferred" with "primary". "primaryPreferred" only reads from the primary when it is available; if the primary is down, it reads from secondaries, which may not have the latest data.

62
MCQeasy

An application needs to perform a series of reads and writes across multiple documents in two collections atomically. The deployment is a replica set running MongoDB 4.2. Which feature should the application use?

A.Multi-document transactions
B.Change streams with resume tokens
C.Capped collections with tailable cursors
D.GridFS for storing large documents
AnswerA

Multi-document transactions allow atomic reads and writes across multiple documents, collections, and databases in a replica set. They provide ACID guarantees for the entire transaction. Since the deployment is a replica set running MongoDB 4.2, multi-document transactions are supported and are the correct feature to achieve atomicity across multiple documents in two collections.

Why this answer

Multi-document transactions in MongoDB 4.2 on replica sets provide ACID guarantees across multiple documents and collections. They are the only feature listed that ensures a series of reads and writes across two collections are applied atomically. The other options are storage or streaming features that do not offer transactional atomicity.

Exam trap

The trap here is assuming that change streams or capped collections can provide atomicity, when they are designed for streaming or fixed-size storage, not for multi-document transactions.

63
MCQhard

When designing a compound shard key in MongoDB, what is the architectural significance of placing a high-cardinality field as the prefix compared to placing a low-cardinality field first?

A.A high-cardinality prefix ensures fine-grained chunk boundaries and even data distribution, whereas a low-cardinality prefix causes massive chunks that cannot be split effectively.
B.A high-cardinality prefix allows the query router to bypass authentication checks on secondary shards, improving overall cluster query response times.
C.A low-cardinality prefix enables the WiredTiger storage engine to cache entire indexes in RAM, eliminating disk I/O bottlenecks entirely.
D.A low-cardinality prefix automatically triggers hashed shard evaluation, bypassing the need for explicit hashing functions during collection creation.
AnswerA

A high-cardinality prefix ensures fine-grained chunk boundaries and even data distribution, whereas a low-cardinality prefix causes massive chunks that cannot be split effectively. Low-cardinality prefixes limit the number of distinct values, creating oversized chunks for each unique value that the balancer cannot split further, leading to severe distribution hotspots.

Why this answer

The shard key prefix dictates how MongoDB organizes and partitions chunk ranges across the cluster. A high-cardinality prefix ensures fine-grained chunk boundaries and prevents massive, unmanageable chunks from forming around repetitive values, which often happens when low-cardinality fields like boolean flags or status codes occupy the leading position.

Exam trap

Candidates often mistakenly prioritize field names or data types over cardinality, failing to realize that low-cardinality prefixes lead to monolithic, unsplittable chunks that degrade cluster performance.

64
MCQhard

Refer to the exhibit. An application queries active user documents frequently, but explainPlan output reveals a COLLSCAN stage. What is the most appropriate remediation step?

A.Modify the application connection string to include readConcern level linearizable.
B.Create a single-field index on the status field using db.collection.createIndex({ status: 1 }).
C.Restart the primary database node to clear the query plan cache and force re-evaluation.
D.Increase the WiredTiger cache size configuration parameter to cache the entire collection in RAM.
AnswerB

Adding an index on the status field provides the query planner with a direct lookup path. Instead of performing an expensive collection scan, the query execution engine leverages an index scan to locate active documents instantaneously.

Why this answer

A COLLSCAN stage indicates that the query engine scanned every document in the collection because no suitable index was found. Creating an index on the filtered field enables the query planner to select an IXSCAN stage, drastically reducing disk reads and improving throughput.

Exam trap

Candidates often suggest multi-key indexes or complex compound indexes when a simple single-field index on the filtered field is the most direct and efficient solution to eliminate a COLLSCAN.

65
MCQeasy

A database is experiencing high latency. You run 'mongotop 5'. What specific insight does this provide compared to 'mongostat' for server administration?

A.Time spent by each collection on read and write operations.
B.A list of the longest-running queries currently in the system.
C.The amount of disk space consumed by each database on the server.
D.The memory distribution between the data and index caches.
AnswerA

The 'mongotop' utility provides a real-time view of the amount of time the mongod instance spends reading from and writing to each collection. This is invaluable for identifying 'hot' collections that may need better indexing, sharding, or schema redesign to alleviate performance bottlenecks on the server.

Why this answer

While mongostat gives a high-level view of server-wide operations and memory, mongotop provides a granular look at where the storage engine is spending its time. It breaks down read and write time by collection, allowing the DBA to identify which specific table is causing the most load on the system.

Exam trap

Examinees often confuse mongotop with mongostat, mistakenly believing mongotop provides system-wide resource utilization metrics like CPU and memory instead of collection-level timing.

66
MCQhard

A DBA is troubleshooting a sharded cluster where the balancer is not migrating chunks even though there is an imbalance. The DBA runs `sh.getBalancerState()` and it returns `true`. Which of the following is the most likely reason the balancer is not migrating chunks?

A.The config servers are in a read-only state.
B.The collection has no indexes on the shard key, so the balancer cannot identify chunks to migrate.
C.The balancer window is configured to a time period outside of the current time.
D.The shard key is hashed, and hashed shard keys prevent the balancer from migrating chunks.
AnswerC

Even if the balancer is enabled, it only runs during the configured balancing window. If the window is set to a time outside the current time, no migrations will occur. The DBA should check `sh.getBalancerWindow()` to see the active window and adjust it if necessary.

Why this answer

The balancer only runs during the configured balancing window. Even if `sh.getBalancerState()` returns `true`, migrations will not occur outside that window. The DBA should check the balancer window settings and ensure they align with the desired migration times.

Other options would either cause broader failures or are not relevant to the balancer's operation.

Exam trap

The trap here is assuming that a `true` balancer state means the balancer is actively migrating chunks at all times, ignoring the effect of the balancing window.

67
MCQhard

A DBA observes that a query with filter { a: 5, b: { $gt: 10 } } and sort { c: 1 } is using a collection scan despite the existence of an index { a: 1, b: 1, c: 1 }. The DBA wants to improve performance. Which action is most likely to allow the index to support both the filter and the sort?

A.Create a new index { a: 1, c: 1, b: 1 } so that the sort field c comes before the range field b.
B.Create a partial index on { a: 1, b: 1, c: 1 } with a filter on b > 10, which will allow the sort to use the index.
C.Add a separate index on { c: 1 } and rely on the query planner to perform an index intersection with the existing index.
D.Modify the query to remove the range condition on b, so the existing index can support the sort on c.
AnswerA

The current index { a: 1, b: 1, c: 1 } cannot support the sort on c because b is a range predicate, which breaks the index prefix for sorting. After the equality on a, the next key is b, but b is not an equality; it is a range. The index can use a and b for filtering, but the sort on c cannot be satisfied because the index order after b is c, but b varies. By reordering the index to { a: 1, c: 1, b: 1 }, the equality on a is followed by the sort key c, allowing the index to provide sorted results. The range on b can then be applied as an index filter on the remaining key. This is the correct approach.

Why this answer

The index { a: 1, b: 1, c: 1 } cannot support the sort on c because b is a range predicate, which means the index order after the equality on a is determined by b, not c. To support both the filter and the sort, the index should be reordered so that the sort field c follows the equality field a, and the range field b comes last. The index { a: 1, c: 1, b: 1 } allows the equality on a to bound the prefix, then the sort on c to be satisfied by the index order, and finally the range on b to be applied as an index filter.

Exam trap

The trap here is assuming that a compound index can support a sort on a field that comes after a range predicate in the index key pattern.

68
Multi-Selecthard

A global IoT platform ingests sensor readings from millions of devices. The team must choose a database that can store semi-structured data, scale horizontally, and provide high write throughput. Which TWO MongoDB features directly support these requirements? (Choose two.)

Select 2 answers
A.Mandatory multi-document ACID transactions for every insert
B.Sharding with a well-chosen shard key
C.Dynamic schema for heterogeneous sensor payloads
D.Strict table-level locking for all write operations
E.Automatic sharding based on the first field alphabetically
AnswersB, C

Sharding with a well-chosen shard key distributes data across multiple shards, enabling horizontal scaling and high write throughput. For IoT workloads, a shard key that spreads writes evenly, such as a hashed device ID, prevents hotspots. This directly supports the platform's need to ingest millions of readings and scale out as device count grows.

Why this answer

Sharding distributes data across shards for horizontal scale and high write throughput, while the dynamic schema accommodates heterogeneous sensor payloads without migrations. Together, these features address the platform's need to ingest semi-structured data from millions of devices and scale out as volume grows.

Exam trap

The trap here is assuming that sharding automatically picks a good shard key, when the key must be chosen deliberately to avoid hotspots.

69
MCQeasy

A server has multiple network interfaces including a public IP and a private management IP. How should the 'net.bindIp' configuration be managed to follow security best practices?

A.Set 'net.bindIp' to '0.0.0.0' to allow connections from any interface.
B.Leave 'net.bindIp' blank to let MongoDB choose the fastest interface.
C.Use the 'net.bindIpAll' setting to simplify the configuration.
D.List only the loopback address and the specific internal IP addresses.
AnswerD

Explicitly listing the internal IPs and '127.0.0.1' ensures that the database only listens for traffic on trusted networks. This administrative control prevents external actors on the public interface from even attempting to connect to the database, providing a critical layer of defense-in-depth for the environment.

Why this answer

Binding MongoDB to the correct network interfaces is a fundamental security task. By default, older versions might bind to all interfaces, exposing the database to the public internet. Best practices dictate binding only to the loopback address and specific internal management or application network IPs to minimize the attack surface.

Exam trap

Candidates often default to binding to 0.0.0.0, which exposes the database to all network interfaces, including public ones, creating a significant security vulnerability by allowing unauthorized remote access.

70
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.

71
MCQhard

A DBA is configuring a replica set with three members: one primary and two secondaries. The DBA wants to ensure that a write concern of { w: 'majority' } is acknowledged only after the write has been applied to a majority of voting members and has been written to the on-disk journal on those members. Which write concern should the DBA use?

A.{ w: 'majority' }
B.{ w: 2, j: true }
C.{ w: 'majority', j: true }
D.{ w: 'majority', j: false }
AnswerC

This write concern combines w: 'majority' with j: true. The w: 'majority' ensures that the write is acknowledged by a majority of voting members in the replica set. The j: true option ensures that the write is written to the on-disk journal before acknowledgment. Together, they meet the requirement: the write is acknowledged only after being applied to a majority of voting members and journaled on those members. This is the correct configuration for durability and consistency. (Explanation length: 65 words)

Why this answer

The requirement is for a write concern that ensures acknowledgment after a majority of voting members have applied the write and written it to the on-disk journal. The write concern { w: 'majority', j: true } achieves both: w: 'majority' dynamically requires a majority of voting members, and j: true forces journaling on those members before acknowledgment. Using a fixed w: 2 may not adapt to membership changes, and omitting j: true does not guarantee journaling. (Explanation length: 65 words)

Exam trap

The trap here is assuming that w: 'majority' alone guarantees journaling, or that w: 2 is always equivalent to majority even when replica set membership changes.

72
MCQeasy

What is the primary benefit of the BSON format in MongoDB?

A.It requires less storage space than raw JSON text.
B.It allows MongoDB to skip fields without parsing them.
C.It forces strict schema validation on all incoming data.
D.It provides native encryption for all document keys.
AnswerB

BSON includes length prefixes for fields and sub-documents. This binary structure allows the database engine to jump directly to specific parts of a document or skip entire fields entirely without deserializing the full payload, which significantly reduces CPU overhead during complex query execution and filtering.

Why this answer

BSON (Binary JSON) is essential to MongoDB because it extends the JSON model by adding support for more data types like Date and BinData while optimizing for traversal. By encoding length prefixes into the binary format, MongoDB can quickly skip over fields without parsing the entire document. This design balance ensures that MongoDB maintains the human-readability benefits of JSON while achieving the performance characteristics necessary for high-throughput, enterprise-scale database operations.

Exam trap

Candidates frequently assume BSON is only for compactness, missing the critical architectural benefit that its binary length-prefixing allows the engine to skip fields without parsing the entire document.

73
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.

74
MCQeasy

In a replica set, what is the 'oplog' and why is it important?

A.A full backup of all data for disaster recovery.
B.A log of all read operations for performance auditing.
C.A capped collection that records all write operations for replication.
D.A temporary cache for incoming client write requests.
AnswerC

The oplog is indeed a capped collection that stores every modification to the data. Secondaries tail this collection continuously, pulling the operations and applying them to their own datasets. This ensures that all members of the replica set eventually reach the same state as the current primary node.

Why this answer

The oplog (operations log) is a capped collection that stores all write operations applied to the database. It is the fundamental mechanism for replication in MongoDB. Secondaries read from the primary's oplog and apply the same operations locally to stay in sync.

Without the oplog, there would be no way to propagate data changes reliably or recover from temporary periods of secondary node disconnection.

Exam trap

Candidates often confuse the oplog with the journal, believing the oplog is for crash recovery rather than the primary mechanism for asynchronous data replication between nodes.

75
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.

Page 1 of 3

Page 2

All pages