Courseiva

MongoDB Certified DBA Associate (C100DBA) — Questions 76–150

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

Page 1

Page 2 of 3

Page 3
76
MCQmedium

You are the DBA for a MongoDB 6.0 replica set with three voting members: rs0-primary (priority 2), rs0-secondary-1 (priority 1), and rs0-secondary-2 (priority 1). The primary fails and is unavailable for an extended period. You need to ensure that rs0-secondary-1 is elected as the new primary instead of rs0-secondary-2. Which action should you take before the primary fails?

A.Set rs0-secondary-1's hidden property to true and rs0-secondary-2's hidden property to false using rs.reconfig().
B.Set rs0-secondary-1's slaveDelay to 0 and rs0-secondary-2's slaveDelay to 3600 using rs.reconfig().
C.Set rs0-secondary-1's priority to 2 and rs0-secondary-2's priority to 0.5 using rs.reconfig().
D.Set rs0-secondary-1's votes to 1 and rs0-secondary-2's votes to 0 using rs.reconfig().
AnswerC

Raising rs0-secondary-1's priority above rs0-secondary-2's priority ensures that, when the current primary is unavailable, rs0-secondary-1 is more likely to win the election. Lowering rs0-secondary-2's priority to 0.5 further reduces its chance of being elected, while still allowing it to vote. This is the correct way to influence election outcomes without making the member unelectable.

Why this answer

Election priority determines which eligible secondary is most likely to win an election. By setting rs0-secondary-1's priority higher than rs0-secondary-2's, you make it the preferred candidate. Lowering rs0-secondary-2's priority to a non-zero value keeps it as a voting member but reduces its election chances.

This approach is the standard way to control primary election outcomes in a MongoDB replica set without making a member unelectable.

Exam trap

The trap here is confusing votes with priority; votes control whether a member can vote in elections, while priority controls which member is more likely to be elected primary.

77
MCQmedium

Which of these best describes MongoDB's approach to the CAP theorem?

A.It is an AP system that ignores consistency entirely.
B.It prioritizes consistency and partition tolerance (CP).
C.It ignores the CAP theorem to improve performance.
D.It is a CA system that never allows partitions.
AnswerB

MongoDB is fundamentally a CP system, as it sacrifices availability during the short window of a primary election to ensure that all reads and writes are consistent. By requiring a majority of nodes to agree, it maintains the integrity of the data across the cluster.

Why this answer

MongoDB is primarily a CP (Consistency and Partition Tolerance) system, though it allows flexible configuration. In the event of a network partition, the system prioritizes consistency by electing a new primary only if a majority can agree. By allowing clients to configure read/write concerns, MongoDB lets developers trade off between immediate consistency and availability, enabling them to tune the database to match the specific requirements of their application's workload and regional deployment.

Exam trap

Candidates often incorrectly label MongoDB as an AP system because of its flexibility, forgetting that the default configuration prioritizes consistency during primary elections in a replica set.

78
MCQeasy

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

A.The database cannot store data if it doesn't have a template.
B.Documents in a collection can have varying fields.
C.The database does not support data types for fields.
D.Indexes can only be created on fields that exist in all documents.
AnswerB

Being schema-less means the database does not enforce a rigid structure. You can have one document with five fields and another with zero, or different field names, within the same collection. This allows for polymorphic data, which is a key advantage for modern, agile application development and data modeling.

Why this answer

Schema-less means that MongoDB does not require an explicit definition of data structures before inserting data. This flexibility allows different documents in the same collection to have entirely different sets of fields. It is a fundamental feature that empowers developers to experiment and evolve their applications in real-time without the overhead of disruptive migrations, which is a significant advantage over traditional relational databases that require rigid DDL statements.

Exam trap

Many candidates mistakenly believe 'schema-less' means MongoDB completely lacks any data structure or ignores data types, rather than allowing documents in a collection to have varying fields.

79
MCQmedium

When adding a new member to an existing replica set, what is the most common reason for the initial sync process to fail if the data set is extremely large?

A.The primary node lacks sufficient RAM for the new member.
B.The oplog size on the primary is smaller than the duration of the sync.
C.The new member's hardware is not identical to the primary.
D.The replica set name does not match on the new member.
AnswerB

If the oplog is too small, the primary will roll over its log entries before the new member finishes copying all data. Once the primary wraps around, the new member loses the pointer to the operations it needs to replay, causing it to fall behind and fail the initial sync process.

Why this answer

Initial sync often fails for large data sets because the oplog on the primary node is too short. If the syncing node takes longer to copy the initial data than the time it takes for the primary to overwrite the necessary oplog entries, the syncing node will fall too far behind and be forced to restart the process, causing an infinite loop of sync failures.

Exam trap

Candidates often blame network latency or hardware issues. They overlook that the primary's oplog is a fixed size and will overwrite history if the sync takes too long.

80
MCQmedium

When would you choose to create a Partial Index instead of a standard index?

A.When you need to ensure the index covers all documents.
B.When only a subset of data is frequently queried.
C.To improve performance for all possible queries.
D.To automatically shard the collection data.
AnswerB

Partial indexes reduce index size by only including documents that meet a filter condition. This is highly effective when your application only queries active or specific subsets of data, leading to smaller index memory footprints and faster performance for those specific, high-frequency query patterns compared to full indexes.

Why this answer

Partial indexes are designed to index only a subset of documents that meet a specific filter expression. They are highly efficient when queries only target a small, specific portion of a large collection. By reducing the size of the index in memory and on disk, partial indexes lower storage costs and decrease the impact on write operations while maintaining query performance for the intended subset of data.

Exam trap

Candidates often choose sparse indexes instead of partial indexes, confusing sparse indexing behavior with the ability to define custom, complex filter expressions for subsets of data.

81
MCQmedium

A financial application requires that read operations never return data that could later be rolled back, even if it means reading from a secondary. The application connects to a replica set with readPreference=secondary. Which read concern level should be used to guarantee that the data read has been acknowledged by a majority of replica set members and cannot be rolled back?

A.readConcern: { level: "local" }
B.readConcern: { level: "available" }
C.readConcern: { level: "majority" }
D.readConcern: { level: "linearizable" }
AnswerC

majority read concern ensures that the data returned has been acknowledged by a majority of replica set members and is therefore durable and cannot be rolled back. When combined with readPreference=secondary, it allows reading from a secondary while still providing the guarantee that the data is majority-committed. This matches the requirement to avoid rollback.

Why this answer

majority read concern guarantees that the data read has been acknowledged by a majority of replica set members, making it durable and not subject to rollback. It can be used with readPreference=secondary, allowing the application to read from secondaries while still ensuring that the data is majority-committed. linearizable is stronger but only works with primary reads.

Exam trap

The trap here is assuming that linearizable read concern can be used with secondary reads, when in fact it is restricted to primary reads only.

82
Multi-Selecthard

Which TWO of the following scenarios are best handled by a Hashed Index?

Select 2 answers
A.Range-based queries on numeric fields.
B.Sharding a collection on a high-cardinality key.
C.Equality lookups on unique values.
D.Sorting results by the indexed field.
E.Text search on long strings.
AnswersB, C

Hashed indexes are the industry standard for sharding keys to ensure an even distribution of data across shards. By hashing the shard key, you prevent the 'hot shard' problem, ensuring that writes are spread out across all nodes in the cluster, which is vital for scalability.

Why this answer

Hashed indexes map the hash of the field value to the document, which is excellent for distributing data evenly across shards. They are ideal for fields with high cardinality that are primarily used for equality lookups. They do not support range-based queries, so they should not be used for fields where inequality filtering (like greater than or less than) is the primary query pattern.

Exam trap

Candidates incorrectly assume hashed indexes support range queries like greater than or less than, leading to poor query optimization and missing results.

83
MCQeasy

A DBA needs to grant a new application service account the ability to read and write data in any database except the admin database on a MongoDB 6.0 replica set. The account should not be able to perform administrative actions such as managing users or shutting down the server. Which built-in role should the DBA assign?

A.root
B.dbOwner on each application database
C.readWriteAnyDatabase
D.readWrite on the admin database
AnswerC

The readWriteAnyDatabase role grants read and write privileges on all databases except the admin, local, and config databases. It does not include administrative privileges such as user management or shutdown. This matches the requirement exactly: the service account can read and write application data but cannot perform administrative actions, and it is restricted from the admin database.

Why this answer

The readWriteAnyDatabase built-in role provides read and write access to all non-system databases without granting administrative privileges. It is the least-privilege role that satisfies the requirement. The other roles either grant excessive privileges, are scoped to a single database, or do not provide the needed access across all application databases.

Exam trap

The trap here is assuming that any read/write role includes administrative rights, or that dbOwner is needed for full access, when readWriteAnyDatabase is sufficient and safer.

84
MCQmedium

Refer to the exhibit. What philosophy regarding client connectivity does this log entry reflect?

A.MongoDB uses a proprietary, non-standard transport protocol.
B.MongoDB prioritizes universal language and driver support.
C.All clients must be authenticated via a central service.
D.The database requires persistent, long-lived connections.
AnswerB

By using standard TCP/IP connections, MongoDB ensures that it can communicate with applications written in any language. The focus on universal connectivity allows developers to build high-performance applications using their preferred tools while maintaining seamless interaction with the database cluster.

Why this answer

The log entry indicates that MongoDB accepts standard TCP connections from client applications. This reflects the philosophy of providing a simple, standard-based interface for developers. By using standard socket-based communication, MongoDB allows drivers to be implemented in virtually any programming language, enabling widespread compatibility and easy integration into diverse application ecosystems without requiring custom protocols or proprietary communication middleware for database interaction.

Exam trap

Students frequently misinterpret log entries as evidence of proprietary middleware requirements, missing that MongoDB intentionally uses standard TCP/IP sockets to ensure universal language and driver compatibility.

85
MCQhard

When enabling access control on a production sharded cluster, what is the most secure method for ensuring internal authentication between cluster components such as mongos and mongod instances?

A.Using a shared keyfile with 600 permissions.
B.Enabling SCRAM-SHA-256 for all administrative users.
C.Configuring LDAP authorization for the __system user.
D.Deploying X.509 certificates for member authentication.
AnswerD

X.509 certificate authentication is the most robust method for internal cluster security. It uses a trusted Certificate Authority to verify the identity of each node. This prevents unauthorized nodes from joining the cluster and allows for easier certificate rotation and better compliance with modern security standards in enterprise environments.

Why this answer

Internal authentication ensures that only trusted components can join the cluster and communicate with each other. While keyfiles are common, X.509 certificates provide a higher level of security by utilizing a Certificate Authority (CA) and providing stronger identity verification. This is standard practice in high-security environments where protecting the internal traffic between nodes is as vital as client-to-server security.

Exam trap

Many candidates default to simpler keyfiles because they are easier to configure, incorrectly assuming keyfiles offer equivalent security to X.509 certificates in high-security production environments.

86
MCQmedium

An application is using a capped collection for logging. What happens when the collection reaches its configured size limit?

A.The collection automatically expands to accommodate new data.
B.The database throws a 'CollectionFull' error for new inserts.
C.The oldest documents are overwritten by new inserts.
D.All existing documents are deleted to free up space.
AnswerC

Capped collections maintain a circular buffer structure. Once the defined size limit or maximum document count is reached, the database automatically removes the oldest documents to make space for incoming data. This process is seamless and allows the application to maintain a constant, manageable storage footprint for its data.

Why this answer

Capped collections follow a 'first-in, first-out' pattern where the oldest documents are automatically overwritten to maintain the specified size. This fixed-size behavior ensures that logging collections do not consume infinite disk space, which is critical for system stability. Application administrators must account for this behavior when designing log management, as it prevents the need for manual cleanup scripts while ensuring the database only retains the most recent relevant operational data for the application.

Exam trap

Candidates frequently mistake capped collections for fixed-size files that stop accepting writes once full. They fail to realize the database automatically overwrites the oldest data to maintain the limit.

87
MCQhard

Refer to the exhibit. What is the implication of setting the priority of n2 to 0?

A.n2 will be excluded from the voting process entirely.
B.n2 will never become the primary node.
C.n2 will stop replicating data from the primary.
D.n2 will be removed from the replica set automatically.
AnswerB

Priority 0 members are ineligible to become primary. This configuration is explicitly used to prevent a specific node from becoming the primary, ensuring that only nodes with higher priority values can take on the primary role during an election, which is useful for regional failover or specialized hardware setups.

Why this answer

A priority of 0 designates a member as a 'passive' node. It can never become the primary, even if all other nodes are down. This configuration is often used for nodes in different data centers to prevent them from taking over as primary, which could cause latency issues for applications.

Understanding this is vital for controlling election behavior and ensuring that the primary node is always located in a preferred, low-latency environment for the application workload.

Exam trap

Candidates often mistake a priority of 0 to mean the node cannot be read from or that it is completely offline, forgetting it only prevents it from becoming primary.

88
MCQmedium

How can you prevent a specific node from becoming a primary in a replica set?

A.Set the node's 'votes' field to 0.
B.Set the node's 'priority' field to 0.
C.Set the node's 'hidden' field to true.
D.Remove the node from the replica set configuration.
AnswerB

A node with a priority of 0 is ineligible to become the primary. This configuration is the standard administrative method to pin a node to a secondary role. It is ideal for nodes that are undersized, geographically distant, or dedicated to tasks that should not be interrupted by election activity.

Why this answer

Setting the 'priority' value to 0 is the standard way to ensure a node never becomes primary. This is commonly done for nodes used for analytical tasks or as disaster recovery targets. It ensures these nodes act solely as passive secondaries, allowing them to serve read requests without ever interfering with the primary election process or causing unexpected failovers.

Exam trap

Candidates often confuse voting rights with eligibility to become primary, mistakenly believing that a priority 0 node cannot vote in elections.

89
MCQmedium

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

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

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

Why this answer

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

Exam trap

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

90
Multi-Selecteasy

Which TWO of the following are primary benefits of implementing sharding in a MongoDB environment?

Select 2 answers
A.Increased storage capacity by spreading data across multiple shards.
B.Automatic failover and high availability for the entire cluster.
C.Improved read and write throughput through parallel processing.
D.Simplified backup and recovery processes for large datasets.
E.Reduced latency for all queries regardless of the shard key used.
AnswersA, C

Each shard in a cluster stores a subset of the total dataset. By adding more shards, the cluster can manage significantly larger volumes of data than any individual replica set could support. This allows for near-infinite growth of the database footprint without requiring massive individual server upgrades.

Why this answer

Sharding provides horizontal scaling, allowing a database to handle loads beyond the capacity of a single server. By distributing data across multiple machines, it increases both the total storage capacity and the aggregate I/O throughput. This architectural pattern is essential for large-scale applications where vertical scaling becomes cost-prohibitive or physically impossible due to hardware limitations on a single node.

Exam trap

Candidates often incorrectly select 'automatic data encryption' or 'high availability' as primary benefits of sharding, failing to distinguish between core sharding features and replica set capabilities.

91
MCQmedium

In a dedicated server environment, what is the primary reason an administrator would choose to manually decrease the 'storage.wiredTiger.engineConfig.cacheSizeGB' below the default value?

A.To increase the speed of BSON document compression.
B.To allow more memory for the filesystem cache to store indexes.
C.To reduce the size of the oplog on the primary node.
D.To accommodate other processes or containers running on the same host.
AnswerD

The most common reason to decrease the cache size is to ensure that other applications, such as monitoring agents, backup tools, or other database instances, have sufficient RAM to function. Without this adjustment, the mongod process might consume too much memory, leading to OOM (Out of Memory) kills.

Why this answer

Effective memory management is the core of MongoDB server administration. While the default cache size is usually optimal, administrators must adjust it when the server hosts other memory-intensive processes. If the operating system or other tools are starved for RAM, it can lead to excessive swapping and system instability, which harms database performance.

Exam trap

Candidates assume the default cache size is always best, ignoring that on shared hosts, MongoDB's aggressive memory usage can trigger OS-level swapping, severely degrading overall system performance.

92
MCQeasy

An application needs to update a user's balance. Which method ensures the operation is atomic for a single document?

A.Read the document, update the value in application code, and save the document.
B.Use the $inc operator with the updateOne method.
C.Wrap the operation in a multi-document transaction every time.
D.Use a global application-level mutex lock before updating.
AnswerB

The $inc operator performs an atomic increment on the server side. Because it is an atomic operation on a single document, it guarantees consistency even under high concurrency, making it the standard and safest method for updating numeric fields like balances in an application.

Why this answer

Atomic updates are a cornerstone of MongoDB's document model. Using update operators like $inc ensures that the update is performed in a single, atomic step at the document level. This prevents race conditions where two threads might attempt to update the same balance simultaneously, ensuring that data integrity is maintained without the need for manual locking mechanisms in the application layer.

Exam trap

Many candidates incorrectly choose findAndModify or multi-document transactions when asked for the simplest atomic operation on a single document, missing the efficiency of updateOne with operators.

93
MCQeasy

A DBA needs a query that returns only the fields name and email from a 'users' collection, filtered by an equality on email, to avoid fetching full documents from disk. Which index design supports this efficiently?

A.A single-field index on email, relying on the query's projection to fetch name from the document.
B.A text index on name and email to cover both fields.
C.A compound index { email: 1, name: 1 } so the query can be covered by the index.
D.A hashed index on email to speed equality matching.
AnswerC

When the index contains every field referenced by the query's filter and projection, MongoDB can return results directly from the index without fetching documents. An index { email: 1, name: 1 } supports the equality on email and supplies name, so the projection is satisfied entirely from index keys, eliminating document fetches and reducing examined documents to index keys only.

Why this answer

A covered query is one whose filter and projection are both satisfied by the index, so no document fetch is needed. Including every projected field in the index, as with { email: 1, name: 1 }, lets the engine return results straight from index keys. Single-field, hashed, and text indexes cannot supply the projected name field, so they cannot cover this query.

Exam trap

The trap here is assuming any index on the filter field avoids document fetches, when coverage requires the index to also contain every projected field.

94
MCQhard

A multi-document transaction is being executed across multiple shards. Which component is responsible for coordinating the transaction and ensuring the all-or-nothing property?

A.The primary node of the config server replica set.
B.The mongos router that initiated the transaction.
C.The shard that contains the first document accessed in the transaction.
D.A specialized 'Transaction Manager' node that must be configured.
AnswerB

The mongos instance serves as the coordinator for the distributed transaction. It tracks which shards are involved, manages the transaction's lifecycle, and executes the commit or abort protocol across all participants. This centralized coordination is necessary to guarantee that the transaction either commits on all shards or none.

Why this answer

Multi-document transactions in a sharded cluster are coordinated by the mongos router where the transaction was initiated. The mongos acts as the transaction coordinator, using a two-phase commit protocol to ensure consistency across the participant shards. This allows applications to maintain ACID guarantees even when data is distributed across a horizontally scaled environment.

Exam trap

Candidates often mistakenly believe that the primary shard or the config servers coordinate multi-document transactions, ignoring the central role of the mongos router in the process.

95
MCQmedium

A logistics company uses MongoDB to track shipments. Each shipment document includes a status field and an array of location updates. The company wants to ensure that when a shipment's status changes to "delivered," the corresponding location update is also recorded atomically. Which MongoDB feature best supports this requirement while adhering to the philosophy of document atomicity?

A.Single-document atomic operations
B.Write concern "majority"
C.Two-phase commit
D.Multi-document ACID transactions
AnswerA

MongoDB guarantees atomicity at the single-document level, meaning that updates to multiple fields within one document are atomic. By embedding the location updates array within the shipment document, the company can update both the status and append a location update in a single atomic operation. This aligns with MongoDB's philosophy of leveraging document atomicity to avoid multi-document transactions when possible.

Why this answer

Single-document atomic operations allow multiple field updates within one document to be atomic, which is ideal when related data is embedded. By storing location updates within the shipment document, the company can atomically change the status and append a new location in one operation, ensuring consistency without multi-document transactions. This leverages MongoDB's core philosophy of designing documents to match access patterns and using document-level atomicity.

Exam trap

The trap here is assuming that multi-document transactions are always required for atomicity, overlooking the power of single-document atomicity when data is embedded.

96
MCQmedium

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

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

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

Why this answer

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

Exam trap

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

97
MCQmedium

A DBA needs to ensure that chunk migrations only occur during a specific maintenance window from 02:00 to 04:00. Which configuration change is required?

A.Update the config.settings collection with an activeWindow document.
B.Use a cron job to call sh.stopBalancer() and sh.startBalancer().
C.Modify the mongod configuration file to include a balancing schedule.
D.Set a TTL index on the chunks collection to expire migrations.
AnswerA

The balancer's schedule is controlled by modifying the 'activeWindow' field within the 'balancer' document of the 'config.settings' collection. This document accepts a start and stop time, and the balancer will only perform migrations during this interval, effectively managing the cluster's resource usage during production hours.

Why this answer

MongoDB allows administrators to define a schedule for the balancer using the settings document in the config database. By setting an activeWindow, you can restrict chunk migrations to periods of low application activity. This prevents the performance overhead of data movement from impacting the user experience during peak hours while still ensuring the cluster stays balanced.

Exam trap

Candidates often incorrectly guess that the balancer is configured via a shell command or a server-wide setting, overlooking the specific requirement to modify the config.settings collection directly.

98
MCQmedium

A high-traffic e-commerce application requires a schema that avoids multi-document transactions where possible to ensure maximum throughput. Which MongoDB philosophy aligns best with this requirement?

A.Normalize all data into separate collections to eliminate redundancy.
B.Implement a strict relational schema to enforce referential integrity.
C.Embed related data in a single document to ensure atomic updates.
D.Use the GridFS specification for all user-generated content.
AnswerC

Embedding data allows the application to update an entire entity in a single atomic write operation. This design pattern reduces the need for application-side joins and avoids the overhead of multi-document transactions. It is the core philosophy behind document-oriented modeling for high-performance, write-heavy workloads.

Why this answer

MongoDB promotes data modeling patterns that prioritize data access patterns. Embedding related data in a single document enables atomic operations on that document, eliminating the need for complex transactions. By co-locating data that is frequently accessed together, applications reduce latency and server overhead, which is critical for high-performance e-commerce platforms.

This design philosophy leverages the document model to ensure consistency and speed within the scope of a single document update.

Exam trap

Many learners incorrectly assume that multi-document transactions should always be preferred for e-commerce, ignoring MongoDB's core philosophy of embedding for atomic updates.

99
MCQmedium

An operations engineer notices that a frequently executed aggregation pipeline fails with a 'Exceeded memory limit for $sort' error. Which index configuration best resolves this memory constraint?

A.Create a wildcard index across all collection fields to capture unpredictable aggregation pipeline projections.
B.Create a compound index matching the query's match filter fields followed by the sort fields in exact order.
C.Increase the global cluster parameter maxInMemorySortBytes beyond the default allocation limit.
D.Enable allowDiskUse on every query connection string globally across the application configuration.
AnswerB

Matching the equality and sort fields within a single compound index enables the storage engine to deliver documents in the precise sorted order required by the pipeline. This eliminates the need for an in-memory sort stage, safely avoiding the strict RAM threshold limits.

Why this answer

MongoDB restricts in-memory operations like sorting to a fixed buffer size. When a query cannot satisfy its sort requirements from an index, it loads documents into memory. Providing a compound index containing the query's equality, range, and sort fields allows the execution engine to stream sorted results directly.

Exam trap

Candidates often create an index only on the sort field, forgetting that the query filter must also be satisfied by the index to avoid an in-memory sort operation.

100
Multi-Selectmedium

A DBA is designing indexes for a collection that stores user activity logs. The collection has fields: user_id, action, timestamp, and metadata (an embedded document). The most common queries are: (1) find all actions for a given user_id sorted by timestamp descending; (2) find all users who performed a specific action within a time range. Which TWO indexes would best support these queries? (Choose two.)

Select 2 answers
A.{ metadata: 1 }
B.{ user_id: 1, timestamp: -1 }
C.{ user_id: 1, action: 1, timestamp: -1 }
D.{ timestamp: 1 }
E.{ action: 1, timestamp: 1 }
AnswersB, E

This index supports query (1) by providing an equality match on user_id and a sort on timestamp descending. The index prefix is user_id, and the sort field follows, so the index can be used efficiently for both filtering and sorting, avoiding an in-memory sort.

Why this answer

The two indexes that best support the queries are { user_id: 1, timestamp: -1 } for query (1) and { action: 1, timestamp: 1 } for query (2). The first provides an equality match on user_id and a sort on timestamp, while the second provides an equality match on action and a range on timestamp. These indexes align with the equality-sort and equality-range patterns, ensuring efficient index usage.

Exam trap

The trap here is creating a single compound index that attempts to cover both queries but fails to support the sort in query (1) because of an extra field in between.

101
Multi-Selecthard

Which THREE of the following are core tenets of the MongoDB philosophy regarding data modeling?

Select 3 answers
A.Normalize data to the third normal form.
B.Store data that is accessed together in the same document.
C.Allow schemas to evolve dynamically without downtime.
D.Always prioritize write consistency over read performance.
E.Design schemas based on application query patterns.
AnswersB, C, E

Embedding related data is a foundational practice in MongoDB. By keeping related information together, the application reduces the number of queries needed, effectively minimizing round-trips to the database and increasing throughput by ensuring all necessary data for an operation is available in one place.

Why this answer

MongoDB's data modeling philosophy emphasizes placing data that is accessed together into the same document (embedding). It promotes flexibility by allowing schemas to be dynamic rather than rigid. Furthermore, it encourages developers to design schemas based on the application's specific query patterns, ensuring that the database layout directly supports the most frequent operations, which leads to optimal performance in high-scale environments where relational joins would otherwise create bottlenecks.

Exam trap

Test-takers often include rigid upfront schema enforcement or mandatory third-normal-form normalization as core tenets, missing the dynamic and query-driven philosophy.

102
MCQmedium

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

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

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

Why this answer

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

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

Exam trap

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

103
MCQmedium

When evaluating the performance of a 'hint' in MongoDB, what should you keep in mind?

A.Hints are always faster than the optimizer's choice.
B.Hints should be used for all production queries.
C.Hints prevent the optimizer from adapting.
D.Hints are only available for aggregation queries.
AnswerC

A hint overrides the query optimizer, forcing it to use a specific index regardless of cost. This prevents the system from choosing better plans as the data distribution changes. This can result in performance regression as the application scales and the original index choice is no longer optimal.

Why this answer

Using a hint forces the optimizer to use a specific index, ignoring its own cost-based selection. While this can sometimes be useful for troubleshooting or very specific cases where the optimizer makes a poor choice, it is generally discouraged because it prevents the database from adapting to data changes. As the data distribution evolves, a hinted index might become suboptimal, leading to degraded performance compared to a dynamic plan.

Exam trap

Test-takers frequently think hints permanently improve performance by hardcoding the best execution path, ignoring the fact that database workloads and data distributions change over time.

104
MCQhard

A collection 'logs' receives continuous inserts and is queried by both timestamp ranges and a rarely used severity field. A DBA creates six indexes to cover every query variant, and now insert throughput has dropped sharply while index sizes dominate the working set. Which action best restores insert throughput while preserving the important query paths?

A.Convert all indexes to hashed indexes to reduce index size.
B.Set the collection's write concern to w:0 to avoid index maintenance waits.
C.Increase the WiredTiger cache size so more indexes stay resident.
D.Drop redundant indexes and consolidate overlapping ones into compound indexes that serve multiple query shapes.
AnswerD

Each additional index must be maintained on every insert, so excess and overlapping indexes multiply write cost and consume cache. Reviewing index usage, removing unused or redundant ones, and merging overlapping prefixes into compound indexes reduces per-insert maintenance while still serving the timestamp range and severity queries. This directly restores insert throughput without sacrificing needed access paths.

Why this answer

Every index adds maintenance work to each insert, update, and delete, so a collection with many overlapping indexes suffers write amplification and cache pressure. Auditing index usage, dropping unused or redundant indexes, and consolidating overlapping prefixes into compound indexes reduces per-write maintenance while keeping the timestamp range and severity access paths covered. Write concern and cache tuning do not remove index maintenance cost.

Exam trap

The trap here is reaching for write concern or cache tuning to fix insert slowdown, when the actual cost is index maintenance from too many overlapping indexes.

105
MCQhard

An application uses a MongoDB driver that supports retryable writes. A write operation is sent to the primary, which applies the write but crashes before sending the acknowledgment. The driver receives a network error. What will the driver do by default?

A.Retry the write indefinitely until it succeeds.
B.Retry the write but with write concern 0 to avoid another failure.
C.Return the error to the application without retrying.
D.Retry the write once, and the server will deduplicate it using the transaction number.
AnswerD

Retryable writes allow the driver to automatically retry a write operation once if it encounters a retryable error, such as a network error. The driver includes a transaction number and session ID, so the server can detect that the retry is the same operation and will not apply it twice. This ensures exactly-once semantics for the write. The driver will retry the write once by default.

Why this answer

Retryable writes automatically retry a write operation once on retryable errors. The driver uses a transaction number and session ID so the server can deduplicate the retry, ensuring the write is applied exactly once. The driver does not retry indefinitely, does not skip retrying, and does not alter the write concern.

The correct behavior is a single retry with deduplication.

Exam trap

The trap here is thinking that retryable writes retry indefinitely or not at all, when in fact they retry exactly once by default using a transaction number for deduplication.

106
MCQeasy

A MongoDB DBA is asked to ensure that the mongod process on a Linux server automatically restarts if it crashes. The server uses systemd. Which command should the DBA run to enable this behavior?

A.systemctl enable mongod
B.Run mongod --fork --logpath /var/log/mongodb/mongod.log
C.systemctl restart mongod
D.Edit the mongod.service unit file to include Restart=always, then run systemctl daemon-reload and systemctl restart mongod
AnswerD

This approach correctly modifies the systemd service unit for mongod to include the Restart=always directive, which tells systemd to restart the service if it exits, regardless of the exit status. After editing the unit file, you must run systemctl daemon-reload to reload the systemd manager configuration, and then restart the service to apply the change. This ensures that if mongod crashes, systemd will automatically restart it. This is the recommended method for achieving automatic restart on failure. (Explanation length: 68 words)

Why this answer

To enable automatic restart of mongod on failure when using systemd, you must modify the service unit file to include Restart=always (or Restart=on-failure). After editing, run systemctl daemon-reload to reload the configuration, and then restart the service. The systemctl enable command only ensures start at boot, not restart on crash.

The other commands are either manual restarts or do not provide automatic restart functionality. (Explanation length: 65 words)

Exam trap

The trap here is assuming that systemctl enable mongod also enables automatic restart on failure, when it only enables start at boot.

107
Multi-Selecteasy

Which THREE components are required to form a functional MongoDB sharded cluster?

Select 3 answers
A.One or more shards to store the data.
B.A replica set of config servers.
C.One or more mongos query routers.
D.A dedicated arbiter node for each shard.
E.A central MongoDB Ops Manager instance.
AnswersA, B, C

Shards are the physical servers or replica sets that contain the subset of the sharded data. They provide the actual storage and processing power for the dataset. In a production environment, each shard is implemented as a replica set to ensure high availability and data redundancy.

Why this answer

A MongoDB sharded cluster consists of three main components: Shards, Config Servers, and Query Routers (mongos). Shards store the actual data, Config Servers store the cluster's metadata and configuration, and Query Routers act as an interface for applications, directing requests to the appropriate shards. Each plays a distinct and vital role in the cluster's operation.

Exam trap

Candidates often mistakenly list 'arbiter nodes' or 'primary nodes' as required components, confusing the architectural requirements of a sharded cluster with those of a standard replica set.

108
MCQmedium

Which MongoDB feature allows an application to receive real-time updates when data changes in a collection?

A.Capped collections
B.Database Profiler
C.Change Streams
D.GridFS
AnswerC

Change Streams allow applications to subscribe to a collection or database and receive notifications whenever a change occurs. This feature is built on top of the oplog and provides a robust, scalable way to implement event-driven architectures, ensuring that the application can react to data changes as they happen.

Why this answer

Change Streams provide an event-driven way for applications to react to data modifications in real time without polling the database. By using the aggregation framework, applications can filter for specific events like inserts, updates, or deletes. This is vital for modern microservices architectures, as it allows downstream systems to keep their caches or search indexes synchronized with the primary data store immediately after a write occurs.

Exam trap

Test-takers frequently confuse Change Streams with regular polling mechanisms or database triggers, failing to realize Change Streams use the aggregation framework for real-time reactive updates.

109
MCQmedium

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

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

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

Why this answer

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

Exam trap

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

110
MCQmedium

In a three-node replica set with default write concerns, what occurs when the primary node experiences a network partition and cannot communicate with the majority of the set?

A.The primary continues accepting writes until the partition is resolved.
B.The primary immediately crashes and shuts down the mongod process.
C.The primary steps down to secondary status, and the set elects a new primary.
D.The secondary nodes force a rollback on the primary node.
AnswerC

When a primary node detects that it can no longer see a majority of the voting members, it transitions to a secondary state. This is essential for cluster health because it allows the remaining nodes in the replica set to hold an election and select a new primary to handle operations.

Why this answer

When a primary loses connectivity to the majority of the replica set, it steps down to secondary status to prevent split-brain scenarios. This process ensures data consistency by requiring a majority of nodes to acknowledge writes. The remaining nodes will initiate an election to choose a new primary, maintaining the availability and integrity of the cluster during the temporary partition event.

Exam trap

Candidates often assume the partitioned primary continues accepting writes, forgetting that the lack of a network majority forces it to step down.

111
MCQmedium

A MongoDB 6.0 sharded cluster has a collection with a ranged shard key on the field 'customerId'. The balancer has been running normally, but the operations team notices that one shard consistently holds significantly more chunks than the others. They want to understand which internal metadata collection the mongos uses to determine chunk distribution and to verify the current chunk-to-shard mapping. Which collection should they query?

A.config.shards
B.config.collections
C.admin.system.version
D.config.chunks
AnswerD

The config.chunks collection in the config database stores the mapping of each chunk to its shard, including the min and max shard key values. Querying config.chunks on a mongos or config server replica set member reveals the exact chunk distribution, allowing the team to confirm which shard owns which ranges and to diagnose imbalance.

Why this answer

Chunk distribution is tracked in the config database, specifically in config.chunks, which maps each chunk's key range to its host shard. To verify which shard holds more chunks, an administrator queries config.chunks. The other collections store different metadata: shard list, collection definitions, or version info, none of which include per-chunk placement.

Exam trap

The trap here is assuming that config.shards contains chunk distribution details, when it only lists shard hosts and states.

112
MCQhard

A MongoDB application requires that reads never see data that could be rolled back, even in the event of a replica set failover. The application also needs to read from secondary nodes to distribute load. Which read concern should be used with a secondary read preference?

A."majority"
B."linearizable"
C."available"
D."local"
AnswerA

"majority" read concern ensures that the data returned has been acknowledged by a majority of replica set members. When used with a secondary read preference, it guarantees that the data read from the secondary is durable and cannot be rolled back during failover. This meets the application's requirement of never seeing rollback-able data.

Why this answer

The application needs to read from secondaries while ensuring that the data returned is not subject to rollback. "majority" read concern guarantees that the data has been acknowledged by a majority of replica set members, making it durable across failover. It is compatible with secondary read preferences, unlike "linearizable", which requires primary reads. Therefore, "majority" is the correct choice.

Exam trap

The trap here is thinking that "linearizable" is the only read concern that prevents rollback, but it cannot be used with secondary reads. "majority" read concern also prevents rollback and works with secondaries.

113
MCQmedium

An administrator notices that the balancer in a MongoDB sharded cluster is repeatedly migrating chunks between two shards, causing performance degradation. The administrator wants to temporarily stop the balancer to investigate. Which command should be used on mongos?

A.db.runCommand({balancerStop: 1}) on the admin database
B.sh.stopBalancer()
C.sh.disableBalancer()
D.sh.setBalancerState(false)
AnswerB

The sh.stopBalancer() method is the correct command to disable the balancer on a sharded cluster. It must be run on mongos and stops the balancer from initiating new chunk migrations. This allows the administrator to investigate the issue without ongoing migrations affecting performance. The balancer can be restarted later with sh.startBalancer().

Why this answer

To temporarily stop the MongoDB balancer, an administrator should run sh.stopBalancer() on mongos. This command disables the balancer and waits for any in-progress migrations to finish, ensuring a clean stop. It is the standard helper for this purpose.

The balancer can be restarted with sh.startBalancer().

Exam trap

The trap here is using the lower-level setBalancerState(false) or an invalid helper name instead of the proper sh.stopBalancer() method that cleanly stops migrations.

114
MCQhard

What is the primary motivation for MongoDB's 'WiredTiger' storage engine to provide document-level concurrency control?

A.To allow for faster reading of large binary objects.
B.To support atomic, multi-document transactions.
C.To increase throughput by reducing write contention.
D.To provide automatic index creation in the background.
AnswerC

Document-level concurrency control minimizes the lock scope, allowing independent writes to proceed in parallel. This significantly increases system throughput, as the database can handle numerous concurrent write requests without forcing them into a single, serialized queue that would otherwise limit performance on high-end hardware.

Why this answer

Early MongoDB versions used a global write lock, which hindered performance by serializing all write requests. Document-level concurrency control allows multiple clients to write to different documents in the same collection simultaneously. This is a critical architectural shift that enables high write throughput, as it drastically reduces contention and allows the database to fully utilize multi-core server architectures, directly supporting MongoDB's promise of high performance at scale.

Exam trap

Candidates often confuse document-level concurrency with transaction isolation, failing to realize the primary goal of document-level locking is to eliminate write contention and increase global throughput.

115
MCQmedium

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

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

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

Why this answer

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

Exam trap

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

116
MCQeasy

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

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

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

Why this answer

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

Exam trap

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

117
MCQmedium

A developer chooses Hashed Sharding for a collection. What is a significant limitation of this sharding strategy compared to Ranged Sharding?

A.Hashed sharding does not support compound shard keys.
B.Hashed sharding requires the shard key field to be a numeric type.
C.Range-based queries on the shard key will result in broadcast operations.
D.Hashed sharding cannot be used with the balancer to move chunks.
AnswerC

In hashed sharding, documents with similar shard key values are unlikely to be stored on the same shard. Consequently, when a query specifies a range of values, the mongos cannot identify a subset of shards and must instead query every shard in the cluster to retrieve the results.

Why this answer

Hashed sharding ensures an even distribution of data across shards by hashing the shard key values, which is excellent for handling monotonically increasing keys. However, because the hash function essentially randomizes the placement of documents, range-based queries cannot be targeted to a single shard. This choice involves a trade-off between write distribution and query efficiency for specific access patterns.

Exam trap

Candidates often assume hashed sharding is faster for all queries. They fail to realize that scattering data randomly makes range-based scans inefficient, forcing the cluster to query every shard.

118
MCQmedium

An application uses a time-series collection. What is the benefit of using the TTL (Time-To-Live) index feature?

A.It automatically creates a new collection for every time period.
B.It ensures data is compressed automatically to save disk space.
C.It allows the database to remove documents based on a timestamp field.
D.It prevents duplicate documents from being inserted into the collection.
AnswerC

A TTL index enables the background removal of documents after a specified number of seconds. This automates data lifecycle management by deleting expired records based on a date-typed field, keeping the collection size manageable without requiring custom application code or manual deletion scripts.

Why this answer

TTL indexes provide an automated mechanism for cleaning up expired data. By setting a TTL index on a date field, MongoDB periodically removes documents that exceed the defined age, which is essential for managing storage and keeping the database size under control in time-series workloads. This reduces administrative manual cleanup tasks and ensures the system maintains a consistent performance level by pruning old, irrelevant data automatically.

Exam trap

Candidates often think TTL indexes are used for query performance optimization, when their primary purpose is strictly data lifecycle management and automated record deletion.

119
MCQmedium

An engineering team must shard a high-volume collection tracking global financial transactions. The chosen shard key is based on a timestamp field containing the exact millisecond of each transaction. Why will this specific shard key choice severely degrade cluster write performance over time?

A.Monotonically increasing timestamp values direct all concurrent write operations exclusively to a single chunk located on the current maximum shard, creating a severe insertion bottleneck.
B.The MongoDB balancer will immediately purge all historical chunks older than twenty-four hours to conserve disk space, resulting in accidental data loss for compliance records.
C.Queries filtering by date ranges will fail because the query router cannot project timestamps across distributed shards without a secondary hashed index on the object identifier.
D.MongoDB will automatically convert the millisecond integers into floating-point numbers, causing precision mismatch errors during chunk migration coordination phases.
AnswerA

Monotonically increasing timestamp values direct all concurrent write operations exclusively to a single chunk located on the current maximum shard, creating a severe insertion bottleneck. Because the cluster cannot distribute active inserts across multiple shards simultaneously, the designated shard experiences severe resource exhaustion while all other cluster shards remain entirely underutilized during peak ingestion periods.

Why this answer

Timestamp shard keys cause write amplification on a single shard because monotonically increasing values always route insertions to the highest chunk in the cluster. This violates key sharding principles by preventing horizontal write scalability. Recognizing insert bottlenecks helps DBAs design balanced, high-throughput architectures using hashed keys or compound prefixes to distribute incoming write operations effectively across multiple cluster shards.

Exam trap

Candidates often believe that high-precision timestamps naturally distribute data well, forgetting that monotonically increasing values send 100% of writes to a single shard chunk.

120
MCQmedium

What is the result of setting the 'votes' configuration to 0 for a specific node in a replica set?

A.The node will no longer replicate data from the primary.
B.The node will be removed from the replica set configuration.
C.The node will not participate in primary elections.
D.The node will automatically become the primary.
AnswerC

By setting votes to 0, the node is explicitly removed from the voting pool. This means the node will not contribute to the quorum required for electing a primary node. This is often used in large replica sets to ensure that voting remains efficient without requiring an excessive number of nodes.

Why this answer

Setting 'votes' to 0 makes the node a non-voting member. It will still replicate data and can serve read queries, but it will never participate in elections for a new primary. This is useful for scaling read capacity without increasing the quorum size, which would otherwise require adding more nodes to maintain a majority in the election process.

Exam trap

Candidates often mistakenly believe that a node with 'votes' set to 0 cannot perform any read operations or data replication, confusing it with a completely offline or disabled node.

121
Multi-Selecthard

Which THREE metrics provided by the 'mongostat' utility are most helpful for identifying a performance bottleneck caused by a high volume of concurrent write operations?

Select 3 answers
A.insert
B.getmore
C.qw
D.vsize
E.update
AnswersA, C, E

The 'insert' column shows the number of insert operations per second. A high value in this column directly indicates a high write load. For a DBA, monitoring this metric alongside others helps determine if the current hardware and storage engine configuration are sufficient for the application's write throughput requirements.

Why this answer

Monitoring server health via mongostat is a daily task for a DBA. High write volumes are best identified by looking at the actual operation counts (insert, update, delete) and the state of the write queue. If the 'qw' (queue write) count is high, it indicates that the storage engine cannot keep up with the incoming write requests.

Exam trap

Candidates often select metrics like 'res' or 'faults' which relate to memory rather than the write queue, missing the direct correlation between 'qw' and write congestion.

122
MCQeasy

A support team reports that a MongoDB 6.0 replica set is experiencing slow queries on a collection where almost every document has a unique value for the field status. A developer suggests creating a hashed index on status to speed up equality lookups. Which outcome should the DBA expect?

A.Hashed indexes provide no benefit for equality queries on high-cardinality fields and should not be used.
B.A hashed index will improve equality query performance but will prevent the use of range queries on status.
C.A hashed index will not improve equality query performance and is primarily intended for even data distribution in sharded clusters.
D.Hashed indexes are ideal for equality lookups and will outperform a standard B-tree index for this query pattern.
AnswerC

Hashed indexes are designed to distribute documents evenly across shards by hashing the shard key value. For a single-node equality lookup, a standard B-tree index is usually sufficient and more versatile because it supports range queries and sorted access. Since the field already has high cardinality, a B-tree index on status would provide efficient equality lookups without the drawbacks of hashed indexes, which cannot be used for range queries.

Why this answer

Hashed indexes are optimized for even distribution of values, which is critical for sharding but not for improving equality query performance on a single replica set. A standard B-tree index on a high-cardinality field like status already provides efficient equality lookups and supports range queries. Therefore, a hashed index would not be the right choice to speed up these queries; it is better suited for shard keys that need uniform distribution.

Exam trap

The trap here is confusing the purpose of hashed indexes, which is even data distribution for sharding, with general query performance optimization.

123
MCQmedium

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

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

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

Why this answer

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

Exam trap

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

124
MCQmedium

When a secondary node is lagging behind the primary, what is the most significant risk to the replica set if the lag time exceeds the length of the oplog?

A.The secondary will trigger an automatic election to become primary.
B.The secondary will enter a 'RECOVERING' state and require a full resync.
C.The primary will automatically reduce its write concern to accommodate the lag.
D.The replica set will automatically increase the oplog size to compensate.
AnswerB

When the oplog entries required for synchronization are no longer present on the primary, the secondary can no longer replicate incrementally. It transitions to a recovering state and must perform a full initial sync, which involves deleting existing data and copying the entire dataset from a healthy replica set member.

Why this answer

If a secondary falls behind the primary beyond the duration of the oplog, the secondary must perform an initial sync. This involves cloning the entire dataset, which is resource-intensive and can significantly degrade performance on the primary. Managing oplog size is a critical operational task to ensure that transient network issues do not force expensive full data copies across the network.

Exam trap

Candidates often guess that lagging nodes simply retry automatically or drop old data, missing the critical requirement for an expensive full resync.

125
MCQhard

Refer to the exhibit. The MongoDB process has crashed due to a storage engine error. What is the most immediate administrative action required to restore service?

A.Run 'db.repairDatabase()' via the shell to free up space.
B.Clear the 'journal' directory files to recover space.
C.Expand the disk volume and restart the mongod process.
D.Modify the 'storage.wiredTiger.engineConfig.cacheSizeGB' setting in the config file.
AnswerC

Expanding the underlying disk volume provides the necessary storage capacity for the database to function. Once additional space is available, the WiredTiger engine can successfully initialize, perform recovery using the journal, and resume normal operations. This is the only safe way to resolve an 'out of space' failure.

Why this answer

The error 'No space left on device' indicates that the disk partition hosting the 'dbPath' directory is completely full. This prevents WiredTiger from writing data, metadata, or logs, causing an immediate shutdown to prevent data corruption. Administrators must free up space on the disk or extend the partition before restarting the service, as the database cannot recover or accept new writes without sufficient storage capacity to manage its internal files.

Exam trap

Exams often lure candidates into attempting a database repair operation first, failing to realize that full disks require immediate space freeing before any recovery command can execute.

126
MCQeasy

Which feature of MongoDB allows it to scale horizontally by distributing data across multiple physical servers?

A.Vertical scaling via hardware upgrades.
B.Sharding to partition data across a cluster.
C.Replica sets for high availability.
D.Index prefixing for faster query execution.
AnswerB

Sharding is the primary mechanism for horizontal scaling in MongoDB. It segments collections into chunks based on a shard key and distributes them across multiple replica sets. This allows the cluster to handle massive datasets and high throughput by parallelizing operations across the distributed nodes in the cluster.

Why this answer

Sharding is the native MongoDB architecture for horizontal scaling, partitioning data into chunks across a cluster of shards. This strategy addresses storage limitations and throughput bottlenecks that single-node or replica set architectures cannot handle. By distributing read and write operations across multiple nodes, sharding maintains performance as datasets grow to terabyte or petabyte scales, fulfilling the philosophy of providing seamless, scalable infrastructure for global applications.

Exam trap

Candidates often incorrectly identify 'Replica Sets' as the tool for horizontal scaling. They fail to realize that replica sets primarily provide redundancy, not distribution of data across servers.

127
MCQhard

Refer to the exhibit. If the primary node fails, which node is most likely to be elected the next primary based on optime?

A.Member[1] will always be elected.
B.Member[2] will likely be elected because it is more up-to-date.
C.No node can be elected because the timestamps are all different.
D.The election will trigger a full re-sync for all nodes.
AnswerB

During an election, nodes compare their oplog state. Member[2] has an optime of 95, making it the most current secondary. Nodes that are more up-to-date are preferred in elections because they minimize the need for rollbacks or data re-syncs, helping to maintain overall cluster consistency and reliability after a failure.

Why this answer

Elections prioritize the node with the most up-to-date data. The optime (operation time) represents the latest operation applied by the node. Member[2] is the most advanced secondary with a timestamp of 95, compared to Member[1] at 90.

Therefore, Member[2] has the highest probability of winning the election, ensuring the new primary has the most current data available in the set.

Exam trap

Candidates often pick the node with the highest priority setting, ignoring that optime takes precedence during primary elections.

128
MCQmedium

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

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

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

Why this answer

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

Exam trap

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

129
MCQeasy

What is the primary function of the oplog in a MongoDB replica set?

A.To store user credentials and authentication data.
B.To record all operations for asynchronous replication.
C.To cache frequently accessed query results in memory.
D.To perform automatic backups for disaster recovery.
AnswerB

The oplog is essential for replication. It acts as a chronological ledger of every write operation performed on the primary. Secondaries continuously tail this log and apply the operations locally, ensuring that they stay synchronized with the primary node, which is the core mechanism behind MongoDB's high availability model.

Why this answer

The oplog, or operation log, is a capped collection that stores all write operations as they are applied to the database. Secondaries read these entries and apply them to their own datasets. This asynchronous replication process ensures that all members of the replica set eventually reach the same state, providing both data redundancy and high availability across the cluster.

Exam trap

Candidates often confuse the oplog with a backup or transaction log meant for point-in-time recovery. It is specifically designed for asynchronous replication between replica set members.

130
MCQeasy

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

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

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

Why this answer

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

Exam trap

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

131
MCQmedium

A social media company is using MongoDB to store user posts and comments. The application needs to retrieve a post along with its most recent comments in a single query. Which data modeling approach best aligns with MongoDB's philosophy to optimize this access pattern?

A.Store comments in a separate collection and use $lookup to join them when needed.
B.Embed a subset of recent comments within the post document and store older comments separately.
C.Store comments in a separate collection and use a manual application-level join to combine them with the post.
D.Embed all comments within the post document to ensure atomic updates and fast reads.
AnswerB

Embedding a subset of recent comments in the post document enables fast retrieval of the post with its most recent comments in a single query, which matches the application's access pattern. Storing older comments separately prevents the document from growing unbounded. This hybrid approach aligns with MongoDB's philosophy of designing for how data is accessed, balancing performance and scalability.

Why this answer

The hybrid approach of embedding recent comments while storing older ones separately optimizes the common access pattern of fetching a post with its latest comments. It leverages MongoDB's flexible schema to keep frequently accessed data together, reducing query latency, while avoiding unbounded document growth. This reflects the core philosophy of modeling based on application access patterns rather than rigid normalization.

Exam trap

The trap here is choosing to embed all comments, which seems simple but can lead to documents exceeding the 16 MB limit and causing write failures.

132
MCQhard

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

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

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

Why this answer

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

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

Exam trap

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

133
MCQmedium

A developer is using the MongoDB Node.js driver and wants to ensure that a write operation is acknowledged by a majority of replica set members and is also written to the on-disk journal before returning success. Which write concern should be specified?

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

This write concern combines majority acknowledgment with journaling. The w: "majority" ensures that a majority of replica set members have applied the write, and j: true ensures that the write is committed to the on-disk journal on those members. This provides the highest level of durability and meets the developer's requirement.

Why this answer

The developer needs both majority acknowledgment and journaling. The write concern { w: "majority", j: true } ensures that a majority of replica set members have applied the write and that it has been written to the on-disk journal on those members. This provides the strongest durability guarantee, preventing data loss even if the primary crashes.

Other options either lack majority acknowledgment or journaling.

Exam trap

The trap here is assuming that w:2 is always equivalent to majority, but in replica sets with more than three voting members, w:2 is not a majority. Only w:"majority" dynamically calculates the majority based on the number of voting members.

134
MCQmedium

What is the primary purpose of an Arbiter in a MongoDB replica set?

A.To serve as a standby node for automatic failover.
B.To participate in elections and help achieve a majority.
C.To provide read-only access to the database.
D.To replicate data from the primary to secondary nodes.
AnswerB

The arbiter exists strictly to vote in elections. In a replica set, elections require a majority of voting members to succeed. By adding an arbiter, you increase the number of voting members, which can help reach that majority quorum without the cost or storage requirements of a full-data node.

Why this answer

An arbiter's sole purpose is to participate in elections to help reach a majority vote without storing any data. By not storing data, it remains lightweight and requires minimal hardware resources, providing a cost-effective way to fulfill the voting requirements of a replica set in scenarios where an extra full-data node is not needed for capacity or redundancy.

Exam trap

Candidates often assume arbiters hold backup copies of data for failover scenarios, confusing them with standard secondary nodes.

135
MCQmedium

During a peak load period, the 'page faults' metric in mongostat increases significantly. What is the most likely administrative cause related to server resources?

A.The working set exceeds the available physical RAM.
B.The number of concurrent connections has reached the 'maxConns' limit.
C.The CPU is throttled due to excessive BSON serialization.
D.The journaling frequency is set too high for the disk subsystem.
AnswerA

When the data and indexes required for active operations no longer fit in the WiredTiger cache and OS filesystem cache, MongoDB must fetch data from disk. This process is much slower than memory access and is recorded as a page fault, leading to increased latency and decreased throughput.

Why this answer

Page faults occur when the mongod process attempts to access data that is not currently in the physical RAM (resident memory). While some page faults are normal, a sudden spike usually indicates that the 'working set' (the data and indexes accessed most frequently) has grown larger than the available RAM, forcing frequent disk reads.

Exam trap

Candidates often confuse 'page faults' in mongostat with OS-level memory paging to disk swap space, forgetting that in MongoDB it specifically refers to documents read from disk files because they are missing from resident RAM.

136
MCQmedium

A healthcare provider is building a patient portal that must remain available even if a data center loses power. The operations team wants the database to continue accepting writes during a single-region outage. Which MongoDB philosophy directly enables this resilience?

A.Relying on periodic logical backups to a cold standby server
B.Automatic failover through replica sets with majority write concern
C.Deploying a standalone mongod instance in each region with application-level conflict resolution
D.Storing all patient data on a single replicated node with manual failover
AnswerB

Replica sets maintain multiple copies of data and automatically elect a new primary if the current one becomes unavailable. Majority write concern ensures that writes are acknowledged by a majority of voting members before returning success, so acknowledged data survives failover. This combination directly provides the continuous write availability and resilience the portal needs.

Why this answer

Replica sets provide automatic failover by electing a new primary when the current one fails, and majority write concern ensures that acknowledged writes are durable across a majority of members. Together, they allow the portal to keep accepting writes during a single-region outage without manual intervention.

Exam trap

The trap here is confusing backup and disaster recovery with high availability, when only automatic failover with durable writes meets continuous write availability.

137
MCQmedium

A DBA needs to automate log rotation on a Linux-based MongoDB server without restarting the mongod process. Which signal or command should be used to ensure the current log file is archived and a new one is started?

A.Send a SIGHUP signal to the mongod PID.
B.Run the 'rotateLogs' command from the admin database.
C.Send a SIGUSR1 signal to the mongod PID.
D.Update the 'systemLog.path' in the YAML config and run 'mongod --reconfig'.
AnswerC

Sending a SIGUSR1 signal to the mongod process triggers the server to close the current log file, rename it with a timestamp, and open a new log file. This is the standard operational procedure for Linux environments to manage log growth without interrupting database services or requiring a full restart.

Why this answer

Log rotation is a critical administrative task that prevents disk space exhaustion and facilitates log analysis. Using the SIGUSR1 signal on Linux systems allows the administrator to rotate logs without any downtime or server restarts. This ensures continuous availability while maintaining manageable file sizes for diagnostic purposes, which is essential for long-term server health and compliance with retention policies.

Exam trap

Candidates often suggest restarting the service to rotate logs, which is unnecessary and causes avoidable downtime, failing to recognize that signal-based rotation is the standard administrative practice.

138
MCQeasy

A DBA is preparing to shard a collection in a MongoDB 6.0 cluster. The collection currently has no indexes other than the default _id index. The chosen shard key is { userId: 1 }. What must the DBA do before running shardCollection?

A.Create an index on userId, because a sharded collection requires a supporting index on the shard key.
B.Convert the shard key to a hashed key first, because ranged shard keys cannot be applied to existing collections.
C.Set the collection to unsharded status and disable the balancer for the duration of the operation.
D.Move the collection to the primary shard and ensure it is empty, because only empty collections can be sharded.
AnswerA

MongoDB requires an index that starts with the shard key fields before a collection can be sharded. If no such index exists, shardCollection fails. Creating an index on userId satisfies this requirement. The index is used to enforce chunk boundaries and support routing, so it must exist prior to the sharding operation.

Why this answer

Before sharding a collection, MongoDB requires an index whose leading fields match the shard key. Without it, the shardCollection command returns an error. Creating an index on userId satisfies this requirement and enables the cluster to manage chunk boundaries and route queries.

Emptying the collection or disabling the balancer is unnecessary and would not satisfy the actual prerequisite.

Exam trap

The trap here is overlooking the index prerequisite and assuming sharding can proceed on a collection with no supporting index for the shard key.

139
MCQmedium

You are monitoring a MongoDB replica set and notice that the replication lag on a secondary is increasing steadily. You suspect that the secondary is unable to keep up with the write load. Which administrative action should you take first to diagnose the issue?

A.Check the output of rs.printSlaveReplicationInfo() to see the lag and the time of the last oplog entry.
B.Restart the secondary to see if the lag clears.
C.Run db.currentOp() on the secondary to see long-running operations.
D.Increase the oplog size on the primary to allow more time for the secondary to catch up.
AnswerA

rs.printSlaveReplicationInfo() provides a quick summary of replication lag for each secondary, including how far behind the secondary is in seconds and the timestamp of its last oplog entry. This is the first step to confirm the lag and identify which secondary is affected. It helps determine if the lag is due to network, disk I/O, or other factors.

Why this answer

The first step in diagnosing replication lag is to quantify it and check the secondary's progress. rs.printSlaveReplicationInfo() provides the lag in seconds and the timestamp of the last oplog entry applied, helping you understand the severity and whether the secondary is making progress. Other actions like restarting or resizing the oplog are premature without diagnosis.

Exam trap

The trap here is jumping to corrective actions like restarting the secondary or resizing the oplog before confirming and understanding the replication lag.

140
MCQmedium

A MongoDB DBA is configuring a new application to connect to a sharded cluster. The application requires that reads are distributed across shards and that the driver automatically routes queries to the appropriate shard based on the shard key. Which component must be included in the connection string to enable this routing?

A.The config server replica set hostnames and ports.
B.The replica set name of the shards.
C.The mongos router hostname and port.
D.The shard replica set hostnames and ports.
AnswerC

In a sharded cluster, mongos routers are responsible for routing queries to the appropriate shards based on the shard key. The application must connect to mongos instances; the driver does not perform shard routing itself. Including the mongos hostname and port in the connection string ensures queries are correctly routed.

Why this answer

In a sharded cluster, applications must connect to mongos routers, which are responsible for routing queries to the appropriate shards based on the shard key. The connection string should include the hostnames and ports of mongos instances. Connecting directly to config servers or shards bypasses the routing layer and is not supported for application traffic.

Exam trap

The trap here is thinking that connecting directly to shards or config servers will enable automatic routing; only mongos provides that functionality.

141
Multi-Selecthard

Which TWO statements accurately describe the behavior and management of orphaned documents in a MongoDB sharded cluster? Choose 2 answers.

Select 2 answers
A.Orphaned documents are documents that remain on a shard after a chunk has been migrated away to another node in the cluster.
B.Administrators can run the cleanupOrphaned command against shard mongod instances to remove leftover documents outside active chunk ranges.
C.Orphaned documents are automatically indexed by the query router and included in all scatter-gather query results by default.
D.The cluster balancer deletes orphaned documents simultaneously across all shards during every active migration window.
E.Orphaned documents prevent the config server from performing routine replica set elections until they are manually purged.
AnswersA, B

Orphaned documents are documents that remain on a shard after a chunk has been migrated away to another node in the cluster. During chunk migrations, source shards retain copies temporarily until cleanup routines safely remove them once migration confirmation is verified.

Why this answer

Orphaned documents are leftover data chunks remaining on a source shard after a chunk migration fails to complete cleanly or before a background cleanup process runs. Understanding how MongoDB handles orphaned documents helps DBAs troubleshoot storage utilization issues and run cleanup tasks safely without risking valid data.

Exam trap

Candidates assume that once a chunk migrates, all data is instantly and completely purged from the source shard without needing any manual or background cleanup.

142
MCQmedium

Why does MongoDB use a 'document' as its fundamental unit of data?

A.It forces the use of fixed-width records for performance.
B.It maps naturally to application objects in code.
C.It ensures that no data can ever be duplicated.
D.It prevents the database from using indexes on fields.
AnswerB

The document model maps directly to common object structures used in languages like JavaScript, Python, and Java. This allows developers to work with data in a format they are familiar with, reducing the overhead of translation and simplifying the process of persisting application-level objects directly into the database.

Why this answer

The document is the natural way to represent complex objects in code. By keeping related information together in one logical unit, MongoDB aligns the database structure with the application's object model. This eliminates the 'impedance mismatch' often found in relational databases, where developers spend significant time mapping objects to tables.

The document model improves performance by allowing the database to retrieve all required data in a single disk read.

Exam trap

Candidates often choose answers related to data compression or network encryption, overlooking how the document structure maps directly to application objects.

143
MCQeasy

Which command is used to verify the current replica set configuration and the state of all members?

A.db.serverStatus()
B.rs.conf()
C.rs.status()
D.db.isMaster()
AnswerC

The 'rs.status()' command returns a document that reports the status of the replica set, including the role of the current node, the status of other members, and critical information such as lag. This is the standard command for monitoring the health and state of a MongoDB cluster.

Why this answer

Checking the replica set status is a routine administrative task to ensure high availability and data consistency. The 'rs.status()' command provides a comprehensive view of the cluster, including the state of every member, the current primary, and the sync lag. This command is the primary diagnostic tool for verifying that the replica set is healthy and that all nodes are correctly communicating with each other.

Exam trap

Test-takers frequently mistake rs.status() for rs.conf(), confusing the runtime state and member health of a replica set with its static configuration document settings.

144
MCQmedium

An application is performing many updates to a document. Which strategy is most effective to avoid fragmentation in the data files?

A.Use the 'compact' command during peak traffic hours.
B.Add padding to the documents to accommodate future growth.
C.Disable the WiredTiger cache periodically.
D.Perform a collection scan after every update.
AnswerB

Adding padding (extra space) to a document ensures that it has room to grow without needing to be relocated on disk. This significantly reduces fragmentation in the data files caused by document moves, which is a key requirement for maintaining high update performance in MongoDB collections.

Why this answer

Document growth is a primary cause of fragmentation in MongoDB collections. When a document grows and no longer fits in its current location on disk, it must be moved to a new location. By pre-allocating space or using an embedding strategy that keeps documents within a predictable size range, administrators can reduce the frequency of document moves, thereby minimizing disk fragmentation and maintaining long-term database performance.

Exam trap

Candidates frequently suggest defragmentation utilities similar to traditional relational databases, ignoring that MongoDB requires document padding or schema redesign to prevent movement overhead.

145
MCQmedium

Why does MongoDB support both embedding and referencing in data modeling?

A.To support legacy relational database imports.
B.To manage data size limits and complex relationships.
C.To force developers to use ACID transactions.
D.To eliminate the need for indexes in the database.
AnswerB

MongoDB documents have a 16MB limit. For large or unbounded datasets, embedding would eventually fail. Referencing allows developers to link documents, maintaining relationships without hitting storage limits or causing data duplication, which is critical for scalable, maintainable application data models.

Why this answer

Embedding is ideal for performance when data is accessed together, but referencing is necessary for handling unbounded data, complex relationships, or avoiding document size limits (16MB). By offering both, MongoDB provides the flexibility to choose the right strategy based on the specific cardinality and access frequency of the data, allowing developers to balance performance and storage constraints effectively without forcing a one-size-fits-all architectural approach.

Exam trap

A common mistake is assuming MongoDB forces either strict embedding or strict normalization, ignoring the flexibility required to handle document size limits and relationships.

146
MCQhard

Refer to the exhibit. The explain output shows a SORT stage wrapping an IXSCAN stage. What is the performance implication of this execution plan?

A.The query is fully optimized because it leverages an index scan for filtering records.
B.The query engine performed an in-memory sort because the index did not support the requested sort order.
C.The query executed a full collection scan across all cluster nodes.
D.The storage engine automatically converted the query into a covered query.
AnswerB

The status index only supports filtering on status. Because the query also requested a sort on created, the database had to sort the resulting documents in memory, which can exceed memory limits and degrade overall execution speed.

Why this answer

When a SORT stage wraps an IXSCAN stage, it means the index used for filtering did not satisfy the sort requirement. The query engine had to load the matching documents into memory to sort them, risking memory limit exceptions on large result sets.

Exam trap

Students often assume that any index usage guarantees optimal performance, overlooking how a SORT stage wrapping an IXSCAN reveals that the index failed to cover the requested sort order.

147
MCQhard

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

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

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

Why this answer

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

Exam trap

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

148
MCQeasy

A developer reports slow queries on a specific collection. You decide to enable the database profiler to capture only queries taking longer than 200ms. Which command configuration achieves this?

A.db.setProfilingLevel(1, { slowms: 200 })
B.db.setProfilingLevel(2, { slowms: 200 })
C.mongod --profile 200 --slowms 1
D.db.adminCommand({ profile: 0, slowms: 200 })
AnswerA

Profiling level 1 instructs MongoDB to log operations that exceed the specified 'slowms' threshold. Setting this to 200 ensures that only queries slower than 200 milliseconds are recorded in the 'system.profile' collection, providing a targeted dataset for performance tuning without overwhelming the server with logging overhead.

Why this answer

The database profiler is an essential administrative tool for diagnosing performance issues. Profiling level 1 is used to capture 'slow' operations without the overhead of capturing every single request (level 2). Setting the 'slowms' threshold to 200 allows the DBA to filter out expected noise and focus on the problematic operations.

Exam trap

Candidates often select the wrong profiling level, confusing level 2 (which captures everything and causes significant performance degradation) with level 1 (the appropriate level for capturing slow queries only).

149
MCQeasy

A three-member replica set has default settings, and all three members are healthy. A DBA needs to perform an index build on the primary during business hours. Which concern should the DBA consider regarding replica set behavior?

A.The index build will cause the primary to step down if any secondary has a replication lag greater than 10 seconds.
B.The index build will only be performed on the primary, and secondaries will build the index lazily during their next election.
C.The index build will be applied to all data-bearing members, and the primary waits for secondaries to finish before committing the index.
D.The index build will be rolled back on the secondaries if any secondary falls behind.
AnswerC

In MongoDB 4.4 and later, index builds are coordinated across all data-bearing replica set members. The primary starts the build and waits for the secondaries to complete their builds before committing the index, ensuring the index is consistent across the set. This behavior affects the duration and resource usage during the build.

Why this answer

In MongoDB 4.4 and later, index builds on replica sets are coordinated: the primary initiates the build, secondaries build concurrently, and the primary waits for all data-bearing secondaries to finish before committing. This ensures index consistency across the set. The operation can be resource-intensive and may impact replication lag temporarily, but it does not roll back or step down due to lag.

Exam trap

The trap here is assuming that index builds only happen on the primary and are later replicated through the oplog, when in fact modern MongoDB coordinates the build across all data-bearing members before committing.

150
MCQhard

A database administrator is configuring a MongoDB replica set. The application requires that writes are acknowledged by a majority of voting members before being considered successful, and that the write is also written to the on-disk journal before acknowledgment. Which write concern specification achieves this?

A.{ w: 1, j: true }
B.{ w: "majority", j: false, wtimeout: 5000 }
C.{ w: "majority", j: true }
D.{ w: "majority", j: false }
AnswerC

This write concern requires acknowledgment from a majority of voting members (w: "majority") and also requires that the write be written to the on-disk journal (j: true) before returning success. This matches the requirement exactly: majority acknowledgment plus journaling. It provides strong durability and is suitable for critical data.

Why this answer

The write concern { w: "majority", j: true } ensures that the write is acknowledged by a majority of voting members and that it is written to the on-disk journal before acknowledgment. This provides both durability and high availability. The other options either lack journaling or lack majority acknowledgment, or both.

Exam trap

The trap here is assuming that w: "majority" alone guarantees journaling, when in fact journaling must be explicitly enabled with j: true.

Page 1

Page 2 of 3

Page 3

All pages