Courseiva

MongoDB Certified DBA Associate (C100DBA) — Questions 151–222

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

Page 2

Page 3 of 3

151
MCQhard

Refer to the exhibit. An administrator attempts to recover a corrupted standalone mongod instance using the --repair flag. Based on the error log output, what is the most appropriate next step for the administrator?

A.Run the --repair command again with the --wiredTigerEngineConfig option.
B.Delete the mongod.lock file and restart the server normally.
C.Restore the data files from the most recent known-good backup.
D.Manually edit the WiredTiger.wt file to fix the offset error.
AnswerC

Since the --repair process failed with a critical WiredTiger read error, the data files are too corrupted for the built-in tools to salvage. The most reliable and standard administrative response is to wipe the corrupted directory and restore the database from a verified backup to ensure consistency.

Why this answer

The --repair flag is a last-resort tool that attempts to salvage data from corrupted files, but it cannot fix severe filesystem or metadata corruption where blocks are missing or unreadable. The 'Short read' error indicates physical or logical corruption that WiredTiger cannot bypass. In this scenario, restoring from a known-good backup is the only reliable way to ensure data integrity.

Exam trap

Candidates often rely on --repair as a 'fix-all' solution, not realizing that severe corruption, such as short reads, indicates physical data loss that repair cannot resolve.

152
MCQmedium

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

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

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

Why this answer

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

Exam trap

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

153
MCQhard

How does the 'Replica Set' architecture influence client application design?

A.Applications must manually hardcode all secondary IP addresses.
B.It enables read distribution across multiple nodes.
C.It mandates that all reads must be 'strong' consistency.
D.It forces the application to implement custom failover logic.
AnswerB

Replica sets allow applications to read from secondary nodes by configuring the 'read preference.' This is a vital feature for scaling read-heavy workloads, as it offloads work from the primary node to the secondaries, provided the application can tolerate the slight potential for eventual consistency.

Why this answer

Replica sets require the driver to be aware of the topology to perform automatic discovery and routing. Since a replica set has a primary node for writes and multiple secondaries for reads, the application must manage read preferences and connection strings correctly. Understanding this architecture is crucial for writing resilient applications that can handle failover events without losing connection or experiencing data consistency issues during node promotions.

Exam trap

Candidates often believe that replica sets are primarily for data backup, overlooking their critical role in enabling read distribution and high availability for client applications.

154
MCQmedium

A DBA is adding a new secondary to an existing replica set. The data set is 2 TB, and the network bandwidth between the new member and the primary is 100 Mbps. The DBA wants to minimize the impact on the primary during the initial sync. Which approach should the DBA take?

A.Configure the new member as a hidden member to reduce its replication load.
B.Increase the oplog size on the primary to accommodate the initial sync.
C.Set the new member's priority to 0 during the initial sync to prevent it from becoming primary.
D.Seed the new member by copying the data files from an existing secondary while it is offline, then start it with the same replica set configuration.
AnswerD

Copying data files from an existing secondary (while it is offline) is a valid method to seed a new member. This avoids the primary having to serve the entire initial sync, distributing the load. It is faster than syncing over a slow network and reduces impact on the primary. The new member must be started with the same replica set name and oplog sufficient to catch up.

Why this answer

Seeding a new member by copying data files from an existing secondary (taken offline) is an efficient way to add a member without burdening the primary with a full initial sync over a slow network. This method leverages local copy speed and avoids consuming primary resources, which is critical when network bandwidth is limited.

Exam trap

The trap here is assuming that changing replica set settings like priority or hidden status will reduce the primary's load during initial sync, but those settings do not affect the data transfer itself.

155
MCQhard

Why does MongoDB choose the BSON format over JSON for storage?

A.BSON is human-readable and easier to debug than JSON.
B.BSON supports fewer data types than standard JSON.
C.BSON allows for faster traversal and efficient type identification.
D.BSON is mandatory for communication with the shell only.
AnswerC

The BSON format includes length headers for every element, allowing the database engine to skip over fields that are not relevant to a query. This binary structure significantly speeds up read/write performance and reduces CPU usage, as the database does not need to parse text strings to identify fields.

Why this answer

BSON (Binary JSON) extends JSON to provide additional data types and efficient encoding for machine processing. By including length prefixes and type information, the database can traverse documents quickly without needing to parse the entire structure. This binary efficiency is crucial for database performance, allowing the storage engine to perform faster lookups, sorting, and field-level operations that would be significantly slower if it had to interpret raw text-based JSON during every query execution.

Exam trap

Test-takers frequently assume BSON is chosen solely to save disk space through compression, overlooking its binary structure optimized for fast machine traversal and type identification.

156
MCQmedium

A MongoDB 6.0 sharded cluster uses a shard key of { region: 1, customerId: 1 } for a global order collection. Most queries filter on customerId only, without region. The operations team observes that nearly every read is a scatter-gather across all shards. What is the most accurate explanation for this behavior?

A.The shard key fields are in the wrong order: customerId must precede region so that queries filtering only on customerId can target a subset of shards.
B.The collection uses hashed sharding, which prevents any targeted reads regardless of which shard key fields appear in the query predicate.
C.The balancer is disabled, so chunks for the customerId values are not distributed and queries cannot be routed to a single shard.
D.The shard key is compound, and MongoDB cannot route queries unless every field in the shard key is present with an equality match.
AnswerA

MongoDB can target queries using a prefix of the shard key. With customerId as the first field, an equality query on customerId matches the prefix and routes to the owning shard, eliminating scatter-gather. With region first, customerId-only queries do not match the prefix and must be broadcast, so reordering the key addresses the observed behavior.

Why this answer

Query targeting on a sharded collection depends on whether the predicate includes a prefix of the shard key. With { region: 1, customerId: 1 }, the leading field is region, so a query filtering only on customerId matches no prefix and mongos broadcasts to all shards. Placing customerId first allows equality queries on customerId to be routed to a single shard, resolving the scatter-gather pattern.

Exam trap

The trap here is assuming that any field contained in a compound shard key enables targeted reads, when only a leading prefix of the shard key can be used for routing.

157
MCQmedium

A development team is building a real-time analytics dashboard that reads from a MongoDB replica set. The dashboard can tolerate slightly stale data but must never show data that could be rolled back. The team also wants to minimize read latency. Which read concern should they use?

A.read concern majority
B.read concern linearizable
C.read concern snapshot
D.read concern local
AnswerA

Read concern majority returns data that has been acknowledged by a majority of replica set members and is therefore durable and cannot be rolled back. It may return slightly stale data, but the dashboard tolerates staleness. It also allows reads from secondaries, which can reduce latency by distributing read load. This is the best fit for the stated requirements.

Why this answer

Read concern majority guarantees that the data returned has been acknowledged by a majority of replica set members and is rollback-safe, while still allowing reads from secondaries to reduce latency. Since the dashboard tolerates slight staleness, this is the ideal balance between consistency and performance.

Exam trap

The trap here is thinking that local read concern is acceptable because the dashboard tolerates stale data, but local does not protect against rollback of uncommitted writes.

158
MCQhard

A DBA is troubleshooting a replica set where the secondary is consistently lagging behind the primary by several hours. The DBA notices that the secondary's optime is far behind the primary's optime, and the secondary's oplog window is only 1 hour. The primary has a heavy write workload. Which action should the DBA take to reduce the replication lag and prevent the secondary from falling off the oplog?

A.Scale the secondary vertically by adding more CPU, RAM, or faster disk I/O.
B.Convert the secondary to an arbiter to reduce its workload.
C.Increase the write concern on the primary to ensure the secondary acknowledges writes.
D.Increase the size of the oplog on the primary and secondaries.
AnswerA

Replication lag often occurs when the secondary cannot apply oplog entries as fast as the primary generates them. Upgrading the secondary's hardware—especially faster disks and more CPU—can increase its oplog application rate, reducing lag. This addresses the underlying performance bottleneck and is the most direct way to improve replication throughput.

Why this answer

Replication lag is typically caused by the secondary's inability to apply oplog entries as quickly as the primary generates them. Improving the secondary's hardware resources—CPU, RAM, and especially disk I/O—increases its oplog application throughput, directly reducing lag. Increasing oplog size only buys time, and write concern does not affect replication speed.

Exam trap

The trap here is focusing on oplog size as the primary solution, when the immediate cause of lag is the secondary's insufficient resources to apply writes; a larger oplog only delays the inevitable resync if lag persists.

159
MCQmedium

An administrator notices that the MongoDB balancer is actively migrating chunks during peak business hours, causing noticeable application latency spikes. What is the standard administrative approach to mitigate this performance impact?

A.Configure a balancer window by updating the settings collection in the config database to restrict migrations to specific off-peak hours.
B.Permanently terminate the mongos process responsible for orchestrating chunk migrations across the cluster nodes.
C.Execute the dropDatabase command on every shard to purge unbalanced chunks instantly and reset the cluster.
D.Disable journaling across all shard replica set members to accelerate background data migration speeds.
AnswerA

Configure a balancer window by updating the settings collection in the config database to restrict migrations to specific off-peak hours. Setting a defined active time window ensures that resource-intensive chunk migrations occur exclusively during scheduled maintenance periods or low-traffic intervals.

Why this answer

Configuring a balancer window restricts chunk migrations to off-peak hours, preventing background balancing traffic from contending with production application workloads. Mastering balancer scheduling controls allows DBAs to maintain cluster health and optimal data distribution without disrupting user experience during critical business hours.

Exam trap

Candidates often think they need to completely disable the balancer during business hours, missing that configuring a maintenance window is the correct granular solution.

160
MCQeasy

A development team is building a mobile application backend using MongoDB. They want to ensure that the application can handle rapid changes to the data model without requiring database downtime or complex migrations. Which MongoDB feature directly supports this requirement?

A.Dynamic schema
B.Horizontal scaling via sharding
C.Change streams
D.Multi-document ACID transactions
AnswerA

MongoDB's dynamic schema allows documents in the same collection to have different fields without requiring alterations to a centralized schema. This means developers can add or remove fields on the fly, supporting agile development and rapid iteration without downtime. The mobile application can evolve its data model simply by writing new documents with different structures, which is a core philosophy of MongoDB.

Why this answer

The dynamic schema is a fundamental MongoDB feature that permits documents within a collection to have varying fields. This flexibility enables developers to iterate quickly, adding or changing fields without performing database migrations or causing downtime. For a mobile application with evolving requirements, this means the backend can adapt seamlessly, aligning with MongoDB's philosophy of developer agility and schema flexibility.

Exam trap

The trap here is confusing schema flexibility with transactional guarantees, which address different concerns.

161
Multi-Selecthard

An administrator needs to create a restricted user for a third-party monitoring tool. The user must be able to perform backups and monitor server status but cannot read actual document data. Which TWO built-in roles should be combined?

Select 2 answers
A.readAnyDatabase
B.dbAdmin
C.backup
D.clusterMonitor
E.hostManager
AnswersC, D

The 'backup' role provides the minimal privileges required to use MongoDB backup tools. It allows the user to read the data for the purpose of backing it up but is designed to be used in conjunction with other roles to limit the user's ability to perform standard ad-hoc queries.

Why this answer

MongoDB's Role-Based Access Control (RBAC) allows for granular permission management. The 'backup' role provides the necessary privileges to use tools like mongodump without granting general read access to all collections. The 'clusterMonitor' role allows the user to run commands like 'serverStatus' and 'top', which are essential for monitoring performance.

Exam trap

Candidates often select roles like 'readAnyDatabase' or 'dbAdmin' which grant excessive permissions, failing to realize that 'backup' and 'clusterMonitor' provide sufficient access without exposing sensitive document data.

162
MCQmedium

Which design principle explains why MongoDB uses a document-oriented model instead of a rigid tabular schema?

A.Normalization of data to reduce storage footprints.
B.Strict enforcement of data types via ACID compliance.
C.Aligning data storage with object-oriented application models.
D.Ensuring all related data is stored in separate collections.
AnswerC

The document model maps naturally to objects in modern programming languages. By storing data as BSON documents, MongoDB removes the impedance mismatch found in ORM layers. This allows developers to work with native data structures, simplifying code logic and accelerating the mapping between database and application.

Why this answer

MongoDB utilizes a document model to align data structures with how applications represent objects, promoting developer productivity and flexibility. By allowing nested structures, developers avoid complex joins required in relational systems, which significantly improves read performance for related data. This philosophy enables schemas to evolve organically as application requirements change, supporting agile development cycles where modifying a table's structure across millions of rows would otherwise impose significant operational overhead or downtime.

Exam trap

Candidates often confuse the document model with simple performance optimization, failing to recognize that the primary driver is the alignment with object-oriented application structures to improve developer productivity and schema flexibility.

163
MCQmedium

You are the DBA for a three-member MongoDB replica set. The primary becomes unreachable due to a network partition, and two secondaries remain in communication. After the election timeout, one secondary is elected primary. What is the required condition for a new primary to be elected?

A.Any secondary with the highest priority automatically becomes primary without needing a majority.
B.The arbiter, if present, must vote and can be the sole voter to elect a primary.
C.The secondary with the most recent oplog entry is elected primary even if it is the only member available.
D.A majority of voting members must be available and able to communicate.
AnswerD

In MongoDB, a new primary is elected only if a majority of voting members are available and can communicate. In a three-member replica set, two voting members must be reachable. This ensures that the replica set does not split-brain and that the elected primary has the most recent data, as it must have the highest optime among the majority.

Why this answer

MongoDB replica sets require a majority of voting members to elect a primary. In a three-member set, two members must be available. The elected primary must have the highest optime among the majority to ensure data consistency.

This mechanism prevents split-brain scenarios and ensures that only one primary can accept writes at a time.

Exam trap

The trap here is assuming that the member with the highest priority or most recent oplog can become primary without a majority quorum.

164
MCQmedium

During routine cluster maintenance, an administrator needs to remove an underperforming shard from a production MongoDB sharded cluster safely. What is the mandatory first step the administrator must execute?

A.Run the removeShard command on the admin database via a mongos connection to initiate the automated chunk draining process.
B.Execute the dropDatabase command on every secondary member of the shard replica set to clear local storage blocks instantly.
C.Manually shut down all mongod processes associated with the target shard before notifying the config server replica set.
D.Run the reshardCollection command to merge all orphaned documents into a single backup file on the primary config server.
AnswerA

Run the removeShard command on the admin database via a mongos connection to initiate the automated chunk draining process. The removeShard command instructs the cluster balancer to begin migrating all data chunks off the specified shard onto remaining active shards in a controlled manner.

Why this answer

Removing a shard safely begins with executing the removeShard command, which initiates the draining process. The cluster balancer automatically migrates all chunks residing on the target shard to other available shards in the cluster, ensuring no user data is lost before the node is decommissioned.

Exam trap

Candidates often assume they must manually stop the balancer or move data off the shard first. In reality, the removeShard command automates the entire migration process internally once triggered.

165
MCQmedium

A financial application must ensure that once a transaction is committed, the data will never be rolled back, even if the primary node crashes immediately after the write is acknowledged. Which write concern should be used?

A.{ w: 0 }
B.{ w: "majority" }
C.{ w: 2 }
D.{ w: 1 }
AnswerB

A write concern of { w: "majority" } ensures that the write is acknowledged by a majority of voting members in the replica set. This means the write is durable across failover because any new primary must be one of the members that acknowledged the write. Therefore, the write cannot be rolled back, satisfying the application's requirement.

Why this answer

The requirement is that committed data must never be rolled back, even if the primary crashes immediately after acknowledgment. Majority write concern guarantees that the write is acknowledged by a majority of voting members, so any newly elected primary will have the write. This prevents rollback during failover.

Other write concerns either provide weaker guarantees or no acknowledgment at all.

Exam trap

The trap here is assuming that any acknowledgment from a secondary (such as w:2) is enough to prevent rollback, but only majority write concern ensures that a majority of voting members have the write, which is necessary to prevent rollback during failover.

166
Multi-Selecthard

Which TWO of the following are essential for maintaining performance in a sharded cluster?

Select 2 answers
A.Selecting a shard key with high cardinality.
B.Hardcoding the shard primary in the application connection string.
C.Regularly monitoring and managing chunk splits.
D.Disabling the balancer during all business hours.
E.Using the same shard key for every collection in the database.
AnswersA, C

High cardinality ensures that data is evenly distributed across shards. A low cardinality key leads to large chunks that cannot be split, causing hotspots where specific shards receive a disproportionate amount of traffic, leading to performance degradation and uneven resource utilization across the cluster.

Why this answer

A well-chosen shard key is the most critical factor for even data distribution, while monitoring chunks ensures that data remains balanced across the cluster. If the shard key is poorly chosen, some shards may become bottlenecks (hotspots), while others remain underutilized. Proper chunk management prevents excessive migration and ensures that query routers (mongos) efficiently route requests to the appropriate shards, maintaining overall system stability and throughput.

Exam trap

Test-takers frequently select low cardinality fields like boolean status flags as good shard keys, completely misunderstanding how poor distribution creates severe cluster bottlenecks.

167
MCQmedium

Which design principle should guide the decision between embedding and referencing?

A.Always embed to prevent any possibility of data duplication.
B.Always reference to keep the database size as small as possible.
C.Model data based on the application's read and write patterns.
D.Use embedding for all data to ensure ACID compliance.
AnswerC

The access pattern dictates the optimal schema. Embedding is preferred for data that is read together to minimize I/O, while referencing is better for large or shared data. This approach puts the application's performance needs first, ensuring that the database schema is an asset rather than a bottleneck.

Why this answer

The primary principle for data modeling in MongoDB is the 'access pattern.' You should model data to match how your application queries it. If data is almost always retrieved together, it should be embedded. If the data is accessed independently or is extremely large, it should be referenced.

This ensures that the system remains performant by minimizing the number of disk reads and network round-trips required to serve requests.

Exam trap

Students frequently rely on relational normalization rules instead of analyzing specific application workloads when deciding how to structure their MongoDB data.

168
MCQeasy

When designing an application, what is the best practice for handling connection pools?

A.Create a new connection for every query.
B.Maintain a long-lived, singleton instance of the MongoClient.
C.Close the connection after every single write operation.
D.Set the connection pool size to zero.
AnswerB

A single MongoClient instance in an application acts as a connection pool. Sharing this instance across the application enables efficient reuse of existing connections, which reduces latency and database load. This is the recommended practice for all production applications to ensure stability and high performance when interacting with MongoDB.

Why this answer

Maintaining a single, long-lived connection pool instance in the application is the most efficient way to manage database connections. Repeatedly creating and destroying connections is extremely expensive, introducing unnecessary latency and resource overhead on both the application server and the database. Proper pool management is a core application administration task that ensures the database handles traffic gracefully without exhausting its maximum configured connection limit due to unnecessary connection churn from the client side.

Exam trap

Candidates often suggest creating a new connection for every request to ensure freshness. This ignores the massive performance overhead of repeated TCP handshakes and authentication on the database server.

169
MCQmedium

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

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

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

Why this answer

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

Exam trap

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

170
Multi-Selectmedium

A financial services company is evaluating MongoDB for a new application that requires strong consistency for critical transactions and high availability across multiple data centers. The team must choose features that align with MongoDB's philosophy of balancing consistency, availability, and partition tolerance. (Choose two.)

Select 2 answers
A.Write concern "w: 1"
B.Read preference "nearest"
C.Read concern "majority"
D.Write concern "majority"
E.Read concern "local"
AnswersC, D

Read concern "majority" ensures that data read has been acknowledged by a majority of replica set members, providing stronger consistency guarantees. This aligns with the need for strong consistency in critical transactions, as it prevents reading uncommitted or rolled-back data. It is a key feature for applications that cannot tolerate stale reads, and it reflects MongoDB's tunable consistency model.

Why this answer

Read concern "majority" and write concern "majority" together provide strong consistency and durability by ensuring that reads and writes are acknowledged by a majority of replica set members. This combination is essential for critical financial transactions that cannot tolerate stale reads or data loss. These features reflect MongoDB's tunable consistency model, allowing the company to balance consistency and availability according to their requirements.

Exam trap

The trap here is assuming that high availability always means using the nearest read preference, which sacrifices consistency.

171
MCQmedium

An application frequently queries a large collection using two fields: 'category' (equality) and 'timestamp' (range). Which index strategy provides the most efficient execution plan?

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

Following the ESR rule, this index allows MongoDB to perform an index seek on the equality field and then efficiently traverse the range of timestamps. This significantly reduces the number of index nodes visited and documents loaded into memory, resulting in optimal query performance and resource utilization.

Why this answer

The ESR (Equality, Sort, Range) rule dictates that equality fields should come first in a compound index, followed by sort fields, and finally range fields. By placing 'category' first, MongoDB eliminates most irrelevant documents immediately. The 'timestamp' field follows, allowing the engine to leverage the index for range filtering.

This minimizes memory usage and prevents costly full collection scans, which is critical for maintaining performance as data volume scales.

Exam trap

Candidates often put the range field before the equality field, violating the ESR rule. This leads to inefficient index usage and slower query performance on large datasets.

172
MCQmedium

An application issues a find query against a sharded collection without including the shard key in the query filter. How does the mongos query router handle this operation?

A.It performs a scatter-gather query by sending the request to all shards in the cluster, merging the results before returning them to the client.
B.It rejects the query immediately with an invalid operation exception to protect cluster performance from unindexed scans.
C.It routes the query exclusively to the primary shard of the database, bypassing all other shards in the infrastructure.
D.It broadcasts the query only to the config server primary, which evaluates the predicate against cached metadata documents.
AnswerA

It performs a scatter-gather query by sending the request to all shards in the cluster, merging the results before returning them to the client. Without the shard key in the filter, mongos lacks routing clues and must query every shard, increasing network overhead and latency.

Why this answer

When a query lacks the shard key, the mongos query router cannot determine which specific shard holds the target document. Consequently, it executes a scatter-gather query, forwarding the request to every shard in the cluster, collecting the responses, and merging them before returning the result to the client.

Exam trap

Candidates incorrectly assume that queries missing the shard key will automatically fail or target only the primary shard, missing that mongos must perform an inefficient scatter-gather operation across all shards.

173
MCQhard

Which capability of MongoDB's document model most significantly distinguishes it from key-value stores?

A.The ability to store binary data as BSON.
B.The ability to index and query nested document fields.
C.The use of a primary key for document retrieval.
D.The support for horizontal scaling across clusters.
AnswerB

MongoDB's secondary indexing allows it to query on nested fields within a document, which key-value stores cannot do. This turns the database into a tool capable of complex data analysis, far beyond the simple get/put functionality provided by standard key-value storage systems.

Why this answer

While key-value stores are limited to looking up data by a single key, MongoDB allows for deep inspection and querying of the document content. MongoDB indexes fields within the document, enables complex aggregation pipelines, and supports ad-hoc queries on any field. This versatility transforms the database from a simple lookup engine into a powerful analytical and transactional system, allowing it to handle diverse workloads that require rich data exploration and complex filtering.

Exam trap

Many candidates mistakenly believe MongoDB's advantage is merely 'storing' data, ignoring that its core superiority over key-value stores is the ability to index and query inside the document structure.

174
MCQhard

Refer to the exhibit. An administrator attempts to execute the shardCollection command but receives the displayed error message. What is the root cause of this failure?

A.The collection lacks a supporting index whose key pattern matches or starts with the fields specified in the shard key definition.
B.The target database has not been enabled for sharding using the enableSharding administrative command.
C.The specified shard key contains an unsupported array field that violates BSON multi-key index constraints.
D.The config server replica set is currently undergoing an election and cannot process metadata write operations.
AnswerA

The collection lacks a supporting index whose key pattern matches or starts with the fields specified in the shard key definition. MongoDB enforces this prerequisite to ensure that every sharded collection has an underlying index capable of efficiently locating document chunk boundaries.

Why this answer

MongoDB requires an explicit index whose prefix matches the designated shard key before sharding a collection. The error indicates that no such index exists on the collection, preventing the query router from establishing the necessary routing boundaries. Creating the correct index prior to running shardCollection resolves this issue.

Exam trap

Candidates often think MongoDB automatically creates the required index when sharding a collection, leading to unexpected command failures due to missing index prefixes.

175
MCQhard

A sharded cluster experiences poor query performance because a targeted query targeting a specific shard key still results in a scatter-gather operation across all shards. What is the root cause?

A.The chunk migration threshold was set too low, causing frequent balancing cycles across shards.
B.The query predicate completely omitted the shard key or its valid prefix fields.
C.The collection was created as unhashed, preventing the mongos router from hashing query inputs.
D.The balancer process was paused, leaving uneven document distribution across cluster shards.
AnswerB

Without the shard key or a valid prefix in the query filter, the mongos query router cannot determine which shard holds the matching data. Consequently, it must broadcast the query to all shards in the cluster, creating an inefficient scatter-gather operation.

Why this answer

To target a specific shard directly, a query must include the exact shard key or a valid prefix of the shard key in its filter predicate. Omitting the shard key forces the mongos router to query every shard in the cluster to assemble the final result set.

Exam trap

Candidates confuse 'querying by the shard key' with 'including the shard key in the query predicate.' Even if you know the shard key, the query must explicitly filter by it.

176
MCQmedium

Why should you avoid creating too many indexes on a single collection?

A.It prevents the use of sharding.
B.It increases the cost of write operations.
C.It automatically disables the WiredTiger cache.
D.It forces queries to use a collection scan.
AnswerB

Each index must be updated whenever a document is inserted, modified, or deleted. Maintaining these B-trees adds synchronous I/O overhead to every write, which can create significant latency and limit the write throughput of the application as the number of indexes grows on the collection.

Why this answer

Every index adds overhead to every write operation (insert, update, delete) because the database must maintain the index structure alongside the collection. Furthermore, indexes consume significant memory, and if the working set (the data and indexes most frequently accessed) exceeds available RAM, the database will experience frequent page faults from disk, leading to severe performance degradation across all types of operations.

Exam trap

Many students mistakenly believe that more indexes only impact disk space, forgetting the significant performance penalty excessive indexes impose on writes and memory usage.

177
MCQeasy

A financial services team is designing a real-time fraud detection system. They need a database that can store alerts with flexible, evolving fields such as device fingerprint, geolocation, and transaction metadata, and that can scale horizontally across many nodes. Which MongoDB philosophy best supports this requirement?

A.Using a single-node in-memory cache with no persistence
B.A rigid normalized schema enforced by the database engine
C.A document-oriented model with dynamic schemas
D.Storing all alert data as large binary blobs outside the database
AnswerC

A document-oriented model with dynamic schemas allows each alert to have its own set of fields without a predefined table structure. This flexibility is essential for evolving fraud signals, and MongoDB's native sharding supports horizontal scaling across many nodes. This directly satisfies the team's need for both flexible data capture and distributed scalability.

Why this answer

MongoDB's document-oriented model with dynamic schemas lets each fraud alert carry different fields without migrations, while built-in sharding enables horizontal scale across nodes. Together, these features directly address the need for flexible, evolving data capture and distributed scalability in a real-time system.

Exam trap

The trap here is assuming that schema flexibility alone solves scaling needs, when horizontal distribution across nodes is equally important.

178
MCQhard

An application serves users in Europe and North America. The DBA wants to ensure that European user data stays on shards located in Europe to comply with data residency laws. Which feature should be used?

A.Replica set tags for read preferences.
B.Zones and Zone Ranges.
C.Hashed sharding with a geo-spatial index.
D.The movePrimary command for each database.
AnswerB

Zones allow you to segment a sharded cluster based on shard key values. By assigning shards to zones (e.g., 'EU_Zone') and mapping specific key ranges to those zones, the balancer ensures that documents are stored only on the shards assigned to the matching zone, fulfilling data locality requirements.

Why this answer

Zones (formerly known as tag-aware sharding) allow administrators to associate specific shard key ranges with particular shards. By tagging shards with geographical identifiers and defining zones for ranges of the shard key, the balancer will automatically move data to the appropriate physical location. This is essential for meeting regulatory requirements and reducing latency.

Exam trap

Candidates often suggest using separate clusters for different regions. While possible, it is significantly more complex than using native MongoDB zones to manage data residency within one cluster.

179
MCQmedium

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

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

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

Why this answer

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

Exam trap

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

180
MCQmedium

When adding a new node to an existing replica set, what is the primary factor that determines how quickly the new member will be able to begin participating in elections?

A.The memory limit set in the configuration file.
B.The amount of data in the dataset and network bandwidth.
C.The number of users defined in the admin database.
D.The version of the MongoDB shell used.
AnswerB

The new member must copy the entire dataset from an existing member before it can apply the oplog to catch up. The time taken for this process is directly proportional to the total size of the data and the speed of the network connection between the nodes.

Why this answer

The speed at which a new replica set member becomes 'secondary' and ready to participate depends on the amount of data it must synchronize from an existing member. Initial sync involves cloning data and applying the oplog. Understanding this process is vital for capacity planning, as adding a large member can put significant I/O and network pressure on the current primary or secondaries, potentially impacting performance for existing application traffic during the synchronization process.

Exam trap

Candidates often guess hardware parameters like CPU speed or RAM size as the primary sync factor, ignoring that dataset volume and network transfer rates dictate initial sync duration.

181
MCQeasy

Which connection string parameter should be used to ensure that an application only reads data from nodes that are considered current and consistent?

A.readPreference=secondary
B.readPreference=primary
C.readPreference=nearest
D.readPreference=secondaryPreferred
AnswerB

Primary read preference forces all operations to go to the primary node, which is the source of truth for all writes. This guarantees the application reads the most recent, consistent data, preventing the issues associated with replication lag that occur when reading from secondary members.

Why this answer

Read preference settings dictate where the application directs its read operations. Using 'primary' ensures that the application always reads the most recent data, avoiding the latency issues inherent in replication lag. This is critical for applications that require strong consistency and cannot tolerate reading stale data, such as financial transactions or inventory management systems, where data accuracy is paramount.

Exam trap

Candidates often confuse 'primary' read preference with 'nearest' or 'primaryPreferred', failing to realize that 'primary' is the only setting that guarantees reading the most current data.

182
MCQeasy

You are a DBA for a MongoDB replica set. A developer asks you to explain what the oplog is and why it is important. What is the correct description?

A.The oplog is a temporary file used during initial sync to transfer data from the primary to a new secondary.
B.The oplog is a cache that stores frequently accessed documents to improve read performance.
C.The oplog is a capped collection that records all write operations and is used by secondaries to replicate data from the primary.
D.The oplog is a log file on disk that records all queries and read operations for auditing purposes.
AnswerC

The oplog (operations log) is a capped collection in the local database that records all write operations. Secondaries continuously read the oplog from their sync source and apply the operations to their own data sets, ensuring replication. It is essential for maintaining data consistency across replica set members.

Why this answer

The oplog is a capped collection in the local database that records all write operations. Secondaries replicate by reading the oplog and applying the operations. This mechanism ensures that all members eventually have the same data, enabling high availability and failover.

Exam trap

The trap here is confusing the oplog with a general log file for auditing or a cache for read performance, when it is specifically a replication mechanism for write operations.

183
MCQhard

A DBA is reviewing a query that performs a sort on a field named score in descending order. The collection has an index { score: 1 }. The query also includes a filter on a field named active with an equality condition. The DBA observes that the query planner chooses a collection scan and performs an in-memory sort. Which index would allow the query to use an index for both the filter and the sort?

A.{ score: -1, active: 1 }
B.{ score: 1, active: 1 }
C.{ active: 1, score: 1 }
D.{ active: 1, score: -1 }
AnswerD

The query has an equality filter on active and sorts by score descending. An index with active first (equality) and score second in descending order allows MongoDB to filter on active and then scan the index in score descending order. This satisfies both the filter and the sort without an in-memory sort. The leading equality field ensures the index can be used efficiently for the filter, and the sort field follows in the correct direction.

Why this answer

The query filters on active with equality and sorts by score descending. The optimal index places the equality field first and the sort field second in the matching direction: { active: 1, score: -1 }. This allows MongoDB to use the index for the filter and to provide the descending sort order directly, avoiding an in-memory sort and improving performance.

Exam trap

The trap here is assuming that an index on the sort field alone is sufficient, when the equality filter field should precede the sort field for efficient compound index usage.

184
MCQeasy

Which property of a field makes it a poor candidate for an index?

A.The field is frequently used in filter criteria.
B.The field contains unique identifiers like UUIDs.
C.The field has very low cardinality.
D.The field is a numeric timestamp.
AnswerC

Low cardinality means the field has very few unique values across a large number of documents. When you search for one of these values, the index may return a huge portion of the collection, making a full collection scan more performant than using the index itself.

Why this answer

Low cardinality fields, such as those with only two or three unique values, provide little benefit when indexed. MongoDB's query optimizer often skips these indexes because a collection scan is usually faster than traversing the B-tree for a large percentage of the dataset. Identifying high-cardinality fields is essential for building effective indexes that genuinely speed up data retrieval rather than just adding overhead to write operations.

Exam trap

Candidates frequently assume indexing every field is universally beneficial, failing to recognize that low-cardinality fields degrade performance and waste resources.

185
MCQeasy

Refer to the exhibit. What is the primary benefit of the data structure shown?

A.It forces data normalization for better storage efficiency.
B.It allows for indexing the array to support efficient queries.
C.It enforces referential integrity between products and tags.
D.It requires a multi-document transaction to update the tags.
AnswerB

MongoDB supports multi-key indexes on array fields. By embedding tags in an array, you can create an index that allows for extremely fast lookups of all documents containing specific tags, which would be difficult and slow to perform if the tags were stored in a separate table.

Why this answer

The exhibit illustrates the use of an array field within a document. By embedding 'tags' directly into the product document, the application can index and query these items without requiring a separate collection or a join. This design effectively demonstrates how the document model supports efficient data retrieval for common filtering patterns, ensuring that the database scales horizontally while keeping related data units cohesive and performant.

Exam trap

Candidates often confuse array indexing with secondary indexes, assuming arrays cannot be queried efficiently, or mistakenly thinking that arrays require a separate collection to maintain relational integrity.

186
MCQhard

Refer to the exhibit. A developer attempts to run a query using both 'tags' and 'location' in a single $and operation. What is the expected behavior regarding index usage?

A.It will always use both indexes simultaneously.
B.It will fail because compound indexes are required.
C.The optimizer may choose an index intersection plan.
D.It will ignore all indexes and scan the collection.
AnswerC

MongoDB's query optimizer can use index intersection to combine multiple single-field indexes to satisfy a query. It will evaluate the candidate indexes and, if the cost analysis indicates that intersection is the most efficient path, it will create a plan using both indexes for the filter.

Why this answer

MongoDB can utilize multiple indexes for a single query through an 'index intersection' execution plan. However, the query optimizer decides whether to perform an intersection or use just one index based on cost. For complex queries involving geo-spatial data and arrays, intersection might be less efficient than a single compound index, and the optimizer may choose a collection scan if intersection costs are deemed too high.

Exam trap

Candidates often assume that MongoDB will always use an index intersection for any query with multiple conditions, ignoring the fact that the optimizer prioritizes single compound indexes over intersection plans.

187
MCQeasy

A MongoDB DBA is investigating replication lag on a secondary member named rs0-2. The DBA runs rs.status() and notices that the 'optimeDate' of rs0-2 is several hours behind the primary's 'optimeDate'. The DBA wants to quickly determine the exact time difference. Which field in the rs.status() output should the DBA compare to calculate the replication lag?

A.The 'optimeDate' field of each member.
B.The 'pingMs' field of each member.
C.The 'lastHeartbeat' field of each member.
D.The 'optime' field of each member.
AnswerA

The 'optimeDate' field in rs.status() provides the human-readable date of the last oplog entry applied by each member. Subtracting the secondary's 'optimeDate' from the primary's 'optimeDate' gives the replication lag. This is the standard method to quickly assess lag.

Why this answer

Replication lag is calculated by comparing the 'optimeDate' of the secondary with that of the primary. The 'optimeDate' field shows the timestamp of the last oplog entry applied by each member, so the difference indicates how far behind the secondary is.

Exam trap

The trap here is confusing network latency metrics like 'pingMs' or heartbeat information with actual replication lag, which is based on oplog application timestamps.

188
MCQmedium

A MongoDB 6.0 replica set is experiencing performance issues during peak hours. The DBA notices that the primary is spending significant time on disk I/O. The DBA wants to identify which collections are generating the most disk reads and writes. Which administrative command should the DBA use?

A.db.currentOp()
B.mongotop
C.db.serverStatus()
D.db.collection.stats()
AnswerB

mongotop reports per-collection read and write activity over time. It shows how much time each collection spends on reads and writes, making it ideal for identifying which collections are causing high disk I/O. By running mongotop during peak hours, the DBA can pinpoint the collections that are the biggest contributors to disk load.

Why this answer

mongotop is designed to provide per-collection read and write statistics, showing how much time each collection spends on these operations. This directly answers the need to find collections generating the most disk I/O. The other tools either provide server-wide metrics, point-in-time operation lists, or static collection statistics that do not reflect active I/O.

Exam trap

The trap here is confusing server-wide I/O metrics with per-collection activity, or assuming that collection stats show real-time I/O when they only show size and structure.

189
MCQmedium

An application requires high write throughput for time-series data indexed by a timestamp field. You observe that all incoming data is being routed to a single shard, creating a write hotspot. Which shard key strategy best resolves this performance bottleneck?

A.Use the timestamp field as a single-field shard key.
B.Implement a range-based shard key using a UUID.
C.Apply a hashed index to the timestamp field as the shard key.
D.Increase the number of mongos instances in the cluster.
AnswerC

Hashed sharding computes a hash of the shard key value and uses that hash to determine the target shard. This ensures that even when timestamp values are strictly increasing, the documents are distributed randomly across shards, preventing the write hotspot and allowing the application to utilize the full write capacity.

Why this answer

Using a hashed shard key distributes documents uniformly across all shards in the cluster regardless of the timestamp value. By hashing the shard key, the balancer ensures that contiguous ranges of data are not sent to the same shard. This strategy is critical in MongoDB sharding to prevent write hotspots and ensure that the disk I/O and CPU utilization are evenly balanced across the entire sharded cluster, effectively scaling write operations horizontally.

Exam trap

Candidates assume that indexing a timestamp field normally prevents hotspots, forgetting that a hashed index is necessary to randomize and distribute sequential writes.

190
MCQhard

A social media platform uses MongoDB to store user posts. Each post document contains an array of comments. The platform's engineers notice that some posts have tens of thousands of comments, causing documents to approach the 16 MB size limit and degrading read performance. They want to redesign the schema to handle this growth while preserving the ability to retrieve a post with its most recent comments efficiently. Which approach best aligns with MongoDB's schema design philosophy?

A.Embed only the most recent comments in the post document and store older comments in a separate collection.
B.Store each comment as a separate document in the same collection and use a parent reference to link them to the post.
C.Increase the document size limit by configuring the storage engine to allow larger BSON documents.
D.Store all comments in a separate collection and use $lookup to join them when needed.
AnswerA

This hybrid approach, known as the outlier pattern or subset pattern, embeds a limited number of recent comments to keep the document small and fast to read, while storing the full set in a separate collection for archival or pagination. It aligns with MongoDB's philosophy by optimizing for the common access pattern (viewing recent comments) while avoiding unbounded document growth. This design balances performance and scalability.

Why this answer

The hybrid approach of embedding recent comments and storing older ones separately aligns with MongoDB's philosophy of designing for the common access pattern while managing document growth. By keeping the post document small, reads remain fast, and the application can still retrieve older comments via a separate query when needed. This pattern is recommended for scenarios with unbounded arrays, balancing performance and scalability.

Exam trap

The trap here is assuming that all related data must be either fully embedded or fully referenced, ignoring hybrid patterns.

191
MCQhard

A MongoDB sharded cluster has a collection with a hashed shard key on the field 'userId'. A query is executed that includes an equality condition on userId. How does mongos route this query?

A.It computes the hash of the userId value and routes the query to the single shard that owns the chunk containing that hash value.
B.It broadcasts the query to all shards because hashed shard keys do not support targeted queries.
C.It routes the query to the primary shard of the cluster because hashed keys always map to the primary shard for reads.
D.It uses the shard key index to identify the shard but must contact the config servers to resolve the chunk location before routing.
AnswerA

With a hashed shard key, MongoDB computes a hash of the field value and uses that hash to determine chunk placement. For an equality query on the hashed field, mongos computes the same hash and can target the exact shard that owns the corresponding chunk. This makes equality queries on the hashed field efficient and targeted to a single shard.

Why this answer

For equality queries on a hashed shard key field, mongos computes the hash of the value and uses its cached chunk metadata to route the query directly to the shard owning that hash range. This enables efficient targeted queries. Scatter-gather only occurs when the query lacks an equality condition on the hashed field.

Exam trap

The trap here is believing that hashed shard keys prevent all targeted queries, when in fact equality queries on the hashed field are efficiently targeted.

192
Multi-Selecthard

Which THREE of the following are core pillars of the MongoDB architecture?

Select 3 answers
A.Horizontal scalability through sharding.
B.Strict, static schema enforcement at the storage layer.
C.High availability through automatic replication.
D.The document-based data model.
E.Global dependency on a single centralized primary node.
AnswersA, C, D

Sharding allows MongoDB to distribute data across multiple servers, enabling the database to scale horizontally. This is a core pillar that allows the system to handle increasing data volume and throughput by adding more shards, which is critical for large-scale distributed applications and high-growth services.

Why this answer

MongoDB's architecture is built on the principles of horizontal scalability, high availability, and developer-focused data modeling. These pillars allow MongoDB to handle massive scale and fluctuating workloads efficiently. By integrating sharding for capacity, replication for reliability, and flexible schemas for agility, the system addresses the common limitations of static relational databases, offering a comprehensive platform for modern, distributed cloud-native applications that require both speed and robustness in dynamic environments.

Exam trap

Candidates often include 'ACID compliance' as a core pillar of the architecture; while true, it is a feature of the storage engine, not a core architectural pillar like sharding or replication.

193
MCQmedium

A company stores IoT sensor data with a high ingestion rate. They use a monotonically increasing timestamp as the shard key. What is the most likely performance bottleneck for this cluster?

A.The balancer will move chunks too frequently, causing network saturation.
B.All new inserts will target the shard holding the highest range of values.
C.Read operations will fail because the query router cannot locate the data.
D.The shard key must be unique, and timestamps often collide in high-volume systems.
AnswerB

In ranged sharding, documents with values exceeding the current max chunk range are placed in the right-most chunk. If the shard key is a timestamp, every new record goes to this single shard. This negates the horizontal scaling benefits of sharding by creating a single point of contention.

Why this answer

Monotonically increasing shard keys like timestamps result in all write operations being directed to a single shard, specifically the one containing the maximum range. This creates a hot shard where the CPU and I/O capacity of one node are exhausted while others remain idle. Understanding write distribution is critical for maintaining high-throughput ingest systems in MongoDB's distributed architecture.

Exam trap

Examinees mistakenly believe that monotonically increasing shard keys distribute writes evenly because new documents are continuously added to the database.

194
MCQeasy

A database administrator is setting up a new sharded cluster and needs to enable sharding on a database named 'sales' before sharding any collections. Which command should be executed on mongos to enable sharding for this database?

A.db.runCommand({enableSharding: "sales"}) on the admin database
B.sh.addShard("sales")
C.sh.shardCollection("sales", {_id: "hashed"})
D.sh.enableSharding("sales")
AnswerD

The sh.enableSharding() method is the correct command to enable sharding on a specific database. It must be run on mongos and takes the database name as an argument. Once enabled, collections within that database can be sharded using sh.shardCollection(). This is a prerequisite step before sharding any collection in the database.

Why this answer

To enable sharding on a database in MongoDB, you must run sh.enableSharding() on mongos with the database name. This marks the database as sharding-enabled in the config servers, allowing collections within it to be sharded. The other commands either shard a collection, add a shard, or use incorrect syntax.

Exam trap

The trap here is confusing the command to enable sharding on a database with the command to shard a specific collection or add a shard to the cluster.

195
MCQmedium

A financial services firm is migrating its reporting application from a relational database to MongoDB. The lead architect argues that MongoDB's schema-less design will eliminate the need for data modeling. Which statement best describes MongoDB's philosophy regarding schema design?

A.Schema design is still essential but is driven by application access patterns rather than normalization rules.
B.Schema design is optional because MongoDB automatically infers and enforces relationships between collections.
C.Schema design should follow third normal form to minimize data duplication and ensure consistency.
D.Schema design is unnecessary because MongoDB validates all documents against a collection schema by default.
AnswerA

MongoDB's philosophy emphasizes that data is accessed together should be stored together, so modeling decisions are based on how the application queries and updates data. This contrasts with relational normalization, which focuses on eliminating redundancy. The schema remains flexible, but a thoughtful design that matches access patterns is critical for performance and scalability.

Why this answer

MongoDB's schema flexibility does not eliminate the need for data modeling; instead, it shifts the focus to designing documents that align with how the application reads and writes data. Embedding and referencing are chosen based on access patterns, not normalization rules. This approach optimizes performance and scalability while still requiring careful planning to avoid pitfalls like unbounded document growth.

Exam trap

The trap here is assuming that schema-less means no schema design is needed, when in fact MongoDB requires deliberate modeling based on application access patterns.

196
MCQeasy

What is the purpose of the 'write concern' in MongoDB?

A.To specify which primary node the write should be directed to.
B.To define the durability and replication requirements for a write.
C.To encrypt the data being written to the database.
D.To automatically compress the data before it reaches the disk.
AnswerB

Write concern allows developers to configure how many replica set members must acknowledge a write before it is considered successful. This provides fine-grained control over durability and consistency, enabling developers to trade off between write performance and the level of data safety they require.

Why this answer

Write concern determines the level of acknowledgement requested from the database for write operations. It is a critical setting for balancing performance against data durability. By choosing the right write concern, developers can ensure that their application meets its specific data safety requirements, whether that means waiting for confirmation from a single node or guaranteeing that the write has been replicated across a majority of the cluster nodes.

Exam trap

Candidates often confuse write concern with read concern, mistakenly believing it dictates how data is retrieved from secondaries rather than acknowledging how the primary confirms the write operation.

197
MCQmedium

A DBA needs to optimize a query that filters on a field with high cardinality, such as email, and also sorts on a low cardinality field, such as country. The query is { email: "user@example.com" } with sort { country: 1 }. Which index would best support this query?

A.{ email: 1 }
B.{ country: 1 }
C.{ country: 1, email: 1 }
D.{ email: 1, country: 1 }
AnswerD

This index supports the query by first filtering on email (equality) and then providing sorted results by country. The index prefix is email, and the sort field country follows. Since email is highly selective, the index will quickly locate the matching document(s) and the sort on country is satisfied by the index order for that email.

Why this answer

The compound index { email: 1, country: 1 } is optimal because it allows an equality match on email, which is highly selective, and then provides sorted results by country. The index order matches the query pattern: equality first, then sort. This avoids an in-memory sort and minimizes the number of documents examined.

Exam trap

The trap here is thinking that the sort field should be first in the index, but with an equality filter on a high-cardinality field, the equality field should lead.

198
MCQeasy

Which read concern provides the strongest consistency guarantee by ensuring the data returned has been acknowledged by a majority of the replica set?

A.local
B.available
C.majority
D.snapshot
AnswerC

The 'majority' read concern ensures that the returned data is committed to a majority of the replica set, preventing reads of data that could be rolled back. It is the best choice for ensuring strong consistency in a distributed system, even if it introduces slightly more latency than lower-consistency levels.

Why this answer

The 'majority' read concern guarantees that the data read has been committed to a majority of the replica set members, ensuring that the read will not be rolled back after a failover. This is essential for applications requiring strong consistency, such as financial systems. DBAs must guide developers on when to trade off performance for this level of consistency to ensure the application behaves correctly under all possible cluster failure scenarios.

Exam trap

Test-takers often confuse read concern 'majority' with write concern 'majority', or assume it guarantees absolute real-time synchronization across all globally distributed nodes.

199
Multi-Selectmedium

Which TWO of the following are benefits of the MongoDB 'document' model over the traditional 'relational' model?

Select 2 answers
A.Built-in support for complex, hierarchical data structures.
B.Requirement for strict normalization of all data.
C.Reduced need for expensive JOIN operations.
D.Guaranteed consistency through mandatory schema migrations.
E.Automatic translation of SQL queries to BSON.
AnswersA, C

The document model supports nesting documents and arrays natively. Relational databases often struggle with this, requiring either many-to-many tables or flat structures that do not accurately represent the data. This hierarchy makes it easier to model real-world data and improves query performance for read-heavy object retrieval.

Why this answer

The document model excels in developer agility and data modeling flexibility. By grouping related data, it optimizes for common access patterns, which enhances read performance by reducing the need for joins. This approach aligns with modern programming paradigms where objects are the primary unit of development, allowing for faster iterations and easier maintenance compared to relational models that require complex schema changes and manual data normalization across multiple tables.

Exam trap

Candidates occasionally select relational benefits like strict ACID guarantees across distributed nodes by default, missing that document models prioritize hierarchical structures and reduced joins.

200
MCQmedium

In a three-node replica set with default write concern w:1, what happens to an unacknowledged write if the primary crashes immediately after receiving the write command but before replicating it to secondaries?

A.The write is automatically rolled back and re-applied when the old primary recovers.
B.The write remains in the local storage of the crashed node and becomes visible upon restart.
C.The write is lost, and the new primary will not contain the data.
D.The replica set triggers an automatic consistency recovery to force the write to other nodes.
AnswerC

Since the write was only acknowledged by the original primary and not replicated to the secondaries, it exists only on the crashed node. When a new primary is elected, it only contains data that was replicated. The original write is effectively discarded from the cluster's consistent view.

Why this answer

With w:1, the primary acknowledges the write as soon as it is applied to its local oplog. If the primary fails before replication, the new primary elected from the remaining nodes will not contain this write. This demonstrates the critical trade-off between performance and durability.

Clients must use w:'majority' to ensure data consistency during failover events, as single-node acknowledgments are insufficient to guarantee persistence against primary loss.

Exam trap

Candidates mistakenly assume that because the primary acknowledged the write, the data is safe, forgetting that a single-node acknowledgment does not guarantee survival during a failover.

201
MCQeasy

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

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

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

Why this answer

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

Exam trap

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

202
MCQhard

A financial services company shards a transactions collection using a ranged shard key on an incrementing timestamp field. Over several months, the cluster develops a single hot shard that receives almost all writes, while the other shards remain nearly idle. Which change best addresses the root cause while preserving efficient range queries on timestamp?

A.Use a compound shard key that combines a low-cardinality prefix such as a hash of the timestamp bucket with the timestamp, or apply a bucketing strategy to spread inserts.
B.Enable the balancer and lower the chunk size to 32 MB so chunks migrate more aggressively during peak hours.
C.Convert the shard key to a hashed key on timestamp, which spreads writes evenly across shards and keeps range queries efficient.
D.Add more shards to the cluster so the hot shard's load is diluted across a larger number of nodes.
AnswerA

Adding a hashed or bucketed prefix distributes inserts across many chunks while preserving the timestamp as a suffix for range queries on time. This directly targets the monotonic write hotspot, keeps the cluster balanced, and still allows efficient range scans because the timestamp remains part of the key and can be used with the prefix for pruning.

Why this answer

A monotonically increasing shard key concentrates all inserts in the highest chunk, creating a single hot shard regardless of cluster size. Introducing a hashed or bucketed prefix spreads writes across many chunks and shards, while retaining timestamp as a suffix preserves efficient range queries. This combination solves the imbalance without sacrificing the query pattern the application depends on.

Exam trap

The trap here is believing that hashed sharding on the timestamp alone is acceptable, when it actually eliminates the efficient range-query capability the application requires.

203
MCQeasy

Which configuration file setting is used to specify the network interface and port that a mongod instance listens on?

A.systemLog
B.storage
C.net
D.processManagement
AnswerC

The 'net' section is the standard configuration block for network-related settings. It specifically contains 'port' to define the listening port and 'bindIp' to restrict the interfaces the server listens on, ensuring that the MongoDB instance can be correctly reached by applications and administrative tools in a network.

Why this answer

The 'net' section in the YAML configuration file provides granular control over how the MongoDB instance communicates over the network. Configuring the 'bindIp' and 'port' is a fundamental step in securing and reaching the database. Properly setting these parameters ensures that the server is accessible only on the intended interfaces, which is a critical security practice to prevent unauthorized access from untrusted networks or public interfaces.

Exam trap

Candidates often confuse the 'net' section with 'replication' or 'systemLog' sections, forgetting that network binding and port configuration are strictly under the 'net' header.

204
MCQmedium

An application frequently queries a large collection by 'user_id' and 'status', sorting the results by 'timestamp'. Which index provides the most efficient execution plan?

A.{ timestamp: 1, user_id: 1, status: 1 }
B.{ user_id: 1, timestamp: 1, status: 1 }
C.{ user_id: 1, status: 1, timestamp: 1 }
D.{ user_id: 1, status: 1 }
AnswerC

This structure follows the ESR rule perfectly. The equality fields appear first, narrowing down the search space, followed by the field required for sorting. This combination allows the query engine to retrieve documents in the desired order without performing an additional, resource-intensive sort operation after fetching the data.

Why this answer

To optimize this query, the ESR (Equality, Sort, Range) rule must be applied. The 'user_id' and 'status' fields are equality filters, while 'timestamp' is used for sorting. An index of {user_id: 1, status: 1, timestamp: 1} allows MongoDB to satisfy the query filters and provide the sort order directly from the index, avoiding a blocking sort operation in memory which is critical for performance on large collections.

Exam trap

Candidates frequently ignore the ESR rule, creating indexes that include fields in the wrong order, which prevents the query engine from efficiently using the index for both filtering and sorting.

205
MCQmedium

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

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

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

Why this answer

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

Exam trap

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

206
MCQeasy

Which read preference allows the application to read from the closest member of the replica set to minimize network latency?

A.primaryPreferred
B.secondary
C.nearest
D.secondaryPreferred
AnswerC

The nearest read preference selects the replica set member with the lowest network latency. This is the ideal setting for applications that prioritize low response times above data consistency, especially in multi-region deployments where connecting to the primary node might introduce significant network delay for the end-user application.

Why this answer

The 'nearest' read preference is specifically designed to reduce latency by targeting the node with the lowest network round-trip time. This is highly effective for global deployments where applications are distributed across regions. Understanding read preferences is fundamental for application administration, as it allows developers to influence traffic distribution and resource utilization across the replica set, ensuring the application remains responsive even when the primary node is geographically distant from the client.

Exam trap

Many confuse 'nearest' with 'primaryPreferred', mistakenly believing nearest prioritizes data freshness over network latency, or vice versa.

207
MCQeasy

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

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

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

Why this answer

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

Exam trap

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

208
Multi-Selecthard

You are administering a MongoDB 6.0 replica set with three members: a primary and two secondaries. You need to perform a rolling maintenance on the secondaries, which involves restarting each secondary one at a time. Which two actions must you take to ensure that the replica set remains available for writes during the maintenance? (Choose two.)

Select 2 answers
A.Disable authentication on the replica set to simplify the restart process.
B.Set the priority of the primary to 0 to prevent it from being re-elected during the maintenance.
C.Restart the secondaries one at a time, waiting for each to fully rejoin and catch up before proceeding to the next.
D.Use rs.stepDown() to force the primary to step down before restarting any secondary.
E.Ensure that the primary remains up and can communicate with a majority of voting members.
AnswersC, E

Restarting secondaries one at a time ensures that at any moment, at least one secondary remains available to maintain a majority with the primary. Waiting for each secondary to fully rejoin and catch up before restarting the next prevents the set from losing majority and ensures that if the primary fails, a fully caught-up secondary can be elected. This is a standard rolling maintenance practice.

Why this answer

To keep a replica set writable during rolling maintenance on secondaries, you must ensure the primary retains a majority of voting members. In a three-member set, this means keeping the primary and at least one secondary online. Restarting secondaries one at a time and waiting for each to catch up before moving to the next maintains majority and data consistency.

This approach allows the primary to continue accepting writes without interruption, provided no other failures occur.

Exam trap

The trap here is thinking that you need to step down the primary or change priorities to perform maintenance; in reality, you only need to maintain majority by keeping the primary and at least one secondary available.

209
MCQhard

What is the purpose of the 'OpLog' in a MongoDB Replica Set?

A.It stores user credentials for database authentication.
B.It provides a mechanism for asynchronous data replication.
C.It is used for storing index definitions and metadata.
D.It acts as a permanent, immutable backup of all data.
AnswerB

The OpLog is the fundamental mechanism for replication. Every write operation on the primary is written to the OpLog, and secondary nodes continuously read from this log to apply the same changes to their local data, ensuring the entire replica set eventually reaches a consistent state.

Why this answer

The OpLog (Operations Log) is a capped collection that records all modifications to the data in the database. It is the core component that allows secondary nodes to replicate data from the primary node. By replaying the operations found in the OpLog, secondaries maintain an identical state to the primary.

Understanding the OpLog is essential for diagnosing replication lag and ensuring the system is effectively synchronized across all nodes in the cluster.

Exam trap

Students often confuse the OpLog with application-level logs or indexing structures, forgetting its specific role in recording write operations for secondary replication.

210
MCQeasy

Which member type in a MongoDB replica set is best suited for a geographically distant data center to provide read-only access without influencing elections?

A.Arbiter
B.Hidden Member
C.Priority 0 Secondary
D.Delayed Secondary
AnswerC

A priority 0 secondary cannot be elected primary, making it perfect for remote sites. It maintains a full copy of the data, which allows it to serve read requests locally. Because it cannot become primary, it eliminates the risk of a high-latency node taking control of the entire cluster's operations.

Why this answer

A priority 0 secondary is ideal for this scenario. By setting the priority to zero, the node is ineligible to become primary, preventing it from participating in elections. This is critical for nodes in remote locations where high latency could disrupt election timing or cause unnecessary re-elections, while still providing low-latency read access to users in that specific geographical region.

Exam trap

Candidates often suggest deploying an arbiter for remote read-only data centers, forgetting that arbiters do not store any data.

211
MCQmedium

A healthcare analytics team stores patient records in MongoDB. Each record includes a nested array of vital sign readings, and the team frequently queries for patients whose latest blood pressure reading exceeds a threshold. They decide to store each reading as a separate document in a readings collection and reference the patient. Which MongoDB design philosophy does this decision contradict?

A.Use server-side JavaScript for all data validation.
B.Store all data in a single collection to simplify sharding.
C.Data that is accessed together should be stored together.
D.Normalize all data to the third normal form to eliminate redundancy.
AnswerC

MongoDB's document model encourages embedding related data that is queried together. By separating readings into another collection, the team forces an extra query or $lookup to retrieve the latest reading, increasing latency and complexity. Embedding the readings array within the patient document aligns with the principle of locality of access, which is central to MongoDB's design philosophy.

Why this answer

The team's choice to reference readings instead of embedding them conflicts with the core MongoDB principle that related data accessed together should be stored together. Embedding the readings array within the patient document would allow a single query to retrieve the latest blood pressure without additional lookups, improving performance and simplifying application logic. This principle guides schema design for locality and efficiency.

Exam trap

The trap here is assuming that any referencing is always wrong, when in fact referencing is appropriate for large, unbounded arrays or data accessed independently.

212
MCQmedium

What is the consequence of having a replica set with only two nodes and no arbiter?

A.The set will automatically double the voting power of the primary.
B.The replica set will be unable to elect a primary if one node fails.
C.The replica set will function normally, but writes will be slow.
D.The primary will become read-only while the secondary remains idle.
AnswerB

With two nodes, a majority is two. If one node fails, only one node remains, which is not a majority of the set. Consequently, the remaining node cannot become or remain a primary, and no new election can occur, effectively stopping all write operations for the application.

Why this answer

A replica set requires a majority of nodes to elect a primary. In a two-node set, a failure of one node makes it impossible to reach a majority, as one out of two is not greater than half. This design limitation is critical because it leads to the loss of a primary and the inability to elect a new one, resulting in a read-only database and complete outage for write operations.

Exam trap

Candidates assume that two nodes are sufficient for high availability, forgetting that a majority (quorum) of 2 is required, which cannot be achieved if one node fails.

213
MCQmedium

A MongoDB replica set has three members: a primary and two secondaries. The DBA needs to perform maintenance on the primary node without causing an election that could lead to data loss. The maintenance requires stopping the mongod process for 30 minutes. Which step should the DBA take first to ensure the primary steps down gracefully and a secondary takes over?

A.Run `rs.stepDown(600)` on the primary.
B.Run `db.shutdownServer()` on the primary.
C.Run `rs.freeze(600)` on the primary.
D.Run `rs.remove()` to remove the primary from the replica set.
AnswerA

The `rs.stepDown()` command forces the primary to step down and become a secondary, triggering an election. The argument 600 specifies the number of seconds the stepped-down member will remain a secondary before it can be elected primary again. This ensures that during the 30-minute maintenance, the original primary does not reclaim primacy, allowing a stable secondary to serve as primary.

Why this answer

To gracefully transfer primacy before maintenance, the DBA should use `rs.stepDown()`, which forces the primary to become a secondary and triggers an election. The optional argument specifies how long the stepped-down member remains ineligible for election, preventing it from immediately reclaiming primacy. This allows a secondary to take over and provides a stable primary during the maintenance window.

Exam trap

The trap here is confusing `rs.freeze()` with `rs.stepDown()`. Freezing a member prevents it from seeking election but does not force a current primary to step down.

214
MCQmedium

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

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

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

Why this answer

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

Exam trap

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

215
MCQmedium

A MongoDB DBA observes that a query with filter { status: "active", created_at: { $gte: ISODate("2024-01-01") } } and sort { created_at: -1 } is performing a collection scan. The collection has an index { status: 1, created_at: -1 }. Which of the following best explains why the index is not being used efficiently?

A.The index prefix is not equality on the leading field, so the sort cannot be satisfied by the index.
B.The index { status: 1, created_at: -1 } should support both the filter and sort; the collection scan indicates a different issue such as index not being built or query planner choosing a different plan.
C.The index is a partial index that excludes documents with status "active", so it cannot be used.
D.The index does not include the sort field as the first field, so the sort cannot use the index.
AnswerB

With equality on status and a range on created_at, the index can efficiently filter and provide sorted results because the index prefix is equality and the sort field follows. A collection scan suggests the index may be missing, invalid, or the planner selected a less efficient plan due to statistics.

Why this answer

The compound index { status: 1, created_at: -1 } is designed to support queries that filter on status with equality and sort on created_at. The index prefix (status) is an equality match, allowing the index to be used for both filtering and sorting. A collection scan indicates that the index might not exist, be invalid, or the query planner chose a different plan due to factors like low selectivity or stale statistics.

Exam trap

The trap here is assuming that the index cannot support the sort because the sort field is not the first field, ignoring the equality condition on the leading field.

216
MCQeasy

Refer to the exhibit. What is the primary function of the node with _id 2 in this replica set?

A.It stores a copy of the data and can serve read queries.
B.It performs automatic failover by hosting a redundant copy of the oplog.
C.It provides a vote during elections to help maintain a majority.
D.It acts as a load balancer for incoming read requests.
AnswerC

The arbiter is specifically configured to provide a voting member to the replica set without requiring the storage overhead of a data-bearing node. By participating in elections, it helps reach a majority of votes, which is required to elect a new primary during failover events in small sets.

Why this answer

An arbiter exists solely to participate in elections and break ties. It does not replicate data or serve read requests, making it a low-resource way to achieve a majority vote in a set. This is crucial for environments where a full-data secondary is cost-prohibitive but high availability is still required to maintain quorum during network partitions.

Exam trap

Candidates often confuse arbiters with secondary nodes, incorrectly assuming that an arbiter replicates data or can be promoted to a primary node during a failover event, which is fundamentally false.

217
MCQmedium

Refer to the exhibit. Which MongoDB philosophy is represented by this document structure?

A.Normalization for maximum data consistency.
B.Data locality for optimized retrieval patterns.
C.Enforcement of a rigid schema using array types.
D.The use of an Oplog to track document changes.
AnswerB

By embedding the array of readings within the document, MongoDB ensures that all information for 'SensorA' is fetched in a single disk read. This follows the philosophy of data locality, where related information is stored physically together to optimize query performance and reduce latency.

Why this answer

This document structure demonstrates the principle of embedding data. Instead of creating a separate collection for sensor readings and joining them via foreign keys, the readings are nested directly within the document. This approach minimizes the need for multi-table joins, which is a key tenet of MongoDB's design to keep data that is accessed together stored together, resulting in faster read performance and simplified application logic for time-series or hierarchical datasets.

Exam trap

Candidates often misidentify the structure as 'denormalization for normalization's sake' or 'relational mapping,' failing to recognize that embedding is specifically about data locality and reducing expensive join operations.

218
Multi-Selecthard

Which THREE components are mandatory architectural parts of every fully functioning MongoDB sharded cluster deployment? Choose 3 answers.

Select 3 answers
A.A config server replica set that stores all cluster metadata, chunk ranges, and routing configuration data.
B.One or more mongos query router instances that interface between client applications and the sharded cluster.
C.Multiple shard replica sets that independently store partitions of the application dataset.
D.A dedicated primary balancer coordinator node running outside the config server replica set to manage migrations.
E.An independent Apache ZooKeeper quorum cluster to coordinate distributed locking across all participating mongod nodes.
AnswersA, B, C

A config server replica set that stores all cluster metadata, chunk ranges, and routing configuration data. The config server tier is mandatory because it maintains the authoritative source of truth regarding database metadata, security settings, and precise chunk range mappings across the entire cluster.

Why this answer

A sharded cluster relies on three core functional components: config servers to maintain cluster metadata, mongos query routers to direct client requests, and shard replicas to store partitioned data safely. Knowing these architecture requirements helps administrators design resilient, highly available production clusters with proper redundancy at every layer of the infrastructure.

Exam trap

Candidates often overlook the config server replica set as a mandatory component, assuming a sharded cluster only requires mongos routers and shard nodes.

219
MCQmedium

A MongoDB DBA is managing a sharded cluster where the collection 'orders' is sharded on the field 'orderDate' using ranged sharding. The DBA needs to add a new shard to the cluster to handle increasing data volume. After adding the shard, the balancer begins migrating chunks. During this migration, the DBA runs a query that includes 'orderDate' and notices increased latency. What is the most likely reason for the increased latency?

A.The config servers are overloaded with metadata updates, causing mongos to delay query routing.
B.The query must now be routed to the new shard, which has not yet been indexed, causing a full collection scan.
C.The shard key 'orderDate' is monotonically increasing, so all new data is going to the new shard, causing a hot spot.
D.The balancer migration process consumes resources on the shards and may cause temporary performance degradation.
AnswerD

Chunk migrations involve copying data from the source shard to the destination shard and updating metadata. This process consumes CPU, memory, and I/O on both shards, which can increase latency for concurrent queries. The impact is temporary and typically resolves once migrations complete.

Why this answer

Adding a shard triggers the balancer to migrate chunks to distribute data. This migration process involves copying data and updating metadata, which consumes resources on the source and destination shards. As a result, concurrent queries may experience increased latency until migrations finish.

The other options describe unrelated issues or misconceptions about indexing and hot spots.

Exam trap

The trap here is attributing latency to the new shard's lack of indexes or config server overload, when the primary cause is resource contention from chunk migration.

220
MCQhard

A global e-commerce platform uses MongoDB with a replica set spanning three data centers. The company wants to ensure that a write is acknowledged by a majority of voting members before it is considered successful, even if one data center experiences a network partition. Which write concern should be configured to meet this requirement?

A.w: 1
B.w: 2
C.w: majority
D.w: 0
AnswerC

w: majority requires that a write be acknowledged by a majority of the voting members in the replica set. In a three-data-center deployment, this ensures that the write is persisted to multiple locations before being considered successful, providing durability even if one data center is partitioned. This aligns with the requirement for high reliability across data centers.

Why this answer

w: majority ensures that a write is acknowledged by a majority of voting members in the replica set, providing strong durability guarantees even in the event of a network partition affecting one data center. This write concern is essential for applications that cannot tolerate data loss and need to maintain consistency across geographically distributed nodes.

Exam trap

The trap here is assuming that w: 2 always provides majority acknowledgment, but in a replica set with more than three members, 2 may not constitute a majority.

221
MCQeasy

Which feature of MongoDB allows it to maintain data consistency during primary node failure?

A.Manual shard intervention by the administrator.
B.Automatic failover via replica set elections.
C.The use of a secondary index for read-only access.
D.The mongos router forcing a global write lock.
AnswerB

Replica set elections are the core mechanism for handling failures. When a primary node fails, the secondary nodes automatically initiate an election to select a new primary. This ensures that the system continues to accept writes with minimal disruption, maintaining consistency across the distributed environment.

Why this answer

MongoDB uses replica sets to ensure high availability. When a primary node becomes unavailable, the remaining nodes in the replica set conduct an election to select a new primary. This process is governed by the consensus algorithm, ensuring that only a node with the most up-to-date data can become the new primary, thereby preventing data loss and maintaining the consistency of the cluster during automated failover scenarios.

Exam trap

Candidates confuse automatic failover with sharding or manual recovery. They often mistake the purpose of replica sets for load balancing rather than high availability and data consistency.

222
Multi-Selecthard

Which THREE factors can significantly impact the time taken for a new primary election?

Select 3 answers
A.The network latency between replica set members.
B.The total number of documents in the largest collection.
C.The heartbeat timeout setting (electionTimeoutMillis).
D.The amount of free RAM available on the primary node.
E.The total number of voting members in the replica set.
AnswersA, C, E

Higher network latency increases the time required for heartbeat signals to travel between nodes. If heartbeats take longer to arrive, the remaining nodes will wait longer before declaring the primary unreachable, thereby increasing the total time elapsed before a new election is triggered and a new primary is established.

Why this answer

The speed of a failover is determined by how quickly nodes detect the primary is down and how quickly they can reach a consensus. Network latency between nodes, the heartbeat interval, and the number of nodes in the set are all critical. Optimizing these factors is necessary for maintaining a high-availability architecture that can recover from outages within the expected time window defined by SLAs.

Exam trap

Candidates often overlook network latency and heartbeat timeouts, incorrectly assuming replica set elections are instantaneous or solely dependent on hardware specs.

Page 2

Page 3 of 3

All pages