Courseiva

CCNA Drivers Tools Transactions Search Questions

39 questions · Drivers Tools Transactions Search topic · All types, answers revealed

1
MCQhard

Refer to the exhibit. What is the impact of setting 'dynamic' to true in this Atlas Search index definition?

A.It forces all documents to follow a strict schema.
B.It prevents the creation of any custom field mappings.
C.It automatically indexes all fields in every document.
D.It disables the indexing of nested object fields.
AnswerC

When dynamic mapping is enabled, Atlas Search scans the documents and automatically indexes every field it encounters. This provides a 'search-everything' capability out of the box, which is extremely convenient for collections where you do not want to manually define mappings for every individual document field.

Why this answer

Setting 'dynamic' to true enables Atlas Search to automatically index all fields in every document within the collection. This is useful for rapid prototyping or collections with unpredictable schemas. However, it can significantly increase the size of the index and consume more resources compared to manual mappings.

Understanding this balance is critical for developers managing performance and cost when dealing with large datasets and varying document structures in search-enabled collections.

Exam trap

Candidates often underestimate the resource cost of dynamic indexing. They assume it is a 'set and forget' feature, ignoring how it bloats the search index and consumes excessive Atlas resources.

2
MCQeasy

A developer needs to perform a point-in-time backup of a MongoDB replica set while the database remains online and serving reads and writes. Which MongoDB Database Tool is designed for this task?

A.mongostat with --discover
B.mongorestore with --archive
C.mongoexport with --query
D.mongodump with --oplog
AnswerD

mongodump with --oplog captures the data plus the oplog entries that occurred during the dump, enabling a point-in-time restore to a specific moment. It runs against a live replica set without requiring downtime, which matches the requirement. The resulting dump can be restored with mongorestore --oplogReplay to reach a consistent point in time, making this the correct tool for online point-in-time backups.

Why this answer

mongodump with --oplog is the MongoDB Database Tool that captures both data and oplog entries during a live dump, enabling point-in-time restore. It runs against a running replica set without downtime. mongoexport lacks oplog capture, mongorestore applies dumps rather than creating them, and mongostat is a monitoring tool, so none of those meet the backup requirement.

Exam trap

The trap here is confusing an export utility with a backup tool, since mongoexport also reads data from a live deployment but cannot support point-in-time recovery.

3
MCQmedium

Refer to the exhibit. An application receives this error during a multi-document transaction. What is the correct approach for the application developer?

A.Terminate the application immediately and alert the database administrator.
B.Retry the specific failed write operation only, outside of the transaction.
C.Use the driver's retry logic to perform the entire transaction again.
D.Hard-code a try-catch block to skip the transaction and log the error.
AnswerC

The 'TransientTransactionError' label explicitly tells the driver that the entire transaction can be safely retried. By wrapping the transaction logic in the 'withTransaction' method, the driver handles the retry loop, including backoff logic, effectively shielding the application from the underlying transient issues while ensuring strict data consistency.

Why this answer

The error label 'TransientTransactionError' indicates that the operation failed due to a temporary state, such as a network glitch or a transient deadlock. In MongoDB, these errors are expected and should be handled by the application through a retry mechanism. Using the driver's built-in 'withTransaction' helper function is the recommended practice, as it automatically implements the necessary retry logic for these types of transient, non-permanent failures.

Exam trap

Candidates attempt to manually catch transient errors and write custom loops, ignoring the built-in driver helper methods specifically designed for this purpose.

4
MCQeasy

What is the primary function of the MongoDB connection pool in a driver?

A.To encrypt data in transit between the client and the server.
B.To reduce the latency of opening new connections.
C.To automatically shard data based on the client's request.
D.To store query results in memory for faster retrieval.
AnswerB

Establishing a new TCP connection and performing the authentication handshake takes significant time. A connection pool keeps these connections open, so when the application needs to perform a query, it can grab an existing, authenticated connection from the pool instantly, drastically improving the response time for database operations.

Why this answer

A connection pool maintains a cache of open connections to the database server. Reopening a connection for every request is expensive due to the overhead of TCP handshakes and authentication. By reusing existing connections, the driver significantly reduces latency and resource consumption, allowing the application to handle high volumes of traffic more efficiently and providing a more stable connection to the database layer.

Exam trap

Candidates often think connection pools limit the total concurrent users an application can support, confusing connection reuse with maximum concurrent thread limits.

5
MCQeasy

A developer wants to query MongoDB Atlas Search for documents where the 'description' field contains the phrase 'wireless headphones'. Which Atlas Search operator should be used to achieve this?

A.The compound operator.
B.The wildcard operator.
C.The phrase operator.
D.The text operator.
AnswerC

The phrase operator is designed to search for a sequence of terms in a specific order. It is ideal for exact phrase matching, such as 'wireless headphones'. It analyzes the field and matches documents where the terms appear consecutively. This operator is part of the Atlas Search aggregation stage.

Why this answer

To search for an exact phrase in Atlas Search, the phrase operator is the correct choice. It ensures that the terms appear in the specified order and adjacent to each other. Other operators like text, wildcard, or compound serve different purposes and would not guarantee phrase matching.

Exam trap

The trap here is confusing the text operator with the phrase operator, assuming that text search automatically respects phrase order.

6
MCQhard

A developer is using mongosh to connect to a MongoDB Atlas cluster and needs to run several administrative commands. The developer wants to ensure that the connection uses the correct authentication database and that all commands are executed with the appropriate read preference. Which mongosh command-line option should be used to specify the authentication database?

A.--readPreference
B.--username
C.--db
D.--authenticationDatabase
AnswerD

The --authenticationDatabase option in mongosh specifies the database against which the user is authenticated. This is essential when the user credentials are stored in a database other than the default (e.g., admin). Without it, authentication may fail if the user is not defined in the default database. It directly addresses the requirement to set the correct authentication database.

Why this answer

In mongosh, the --authenticationDatabase option explicitly sets the database used for authentication. This is necessary when user credentials reside in a database other than the default (often admin). Other options like --db or --readPreference affect connection behavior but not authentication.

Specifying the correct authentication database ensures that the provided username and password are validated against the intended database.

Exam trap

The trap here is confusing the authentication database with the default database to use after connection.

7
MCQhard

A developer is using the MongoDB Node.js driver to perform a multi-document transaction that includes a read operation followed by a write operation. The developer wants to ensure that the read sees a consistent snapshot of the data and that the write is atomic with the read. Which of the following read concerns should be used for the read operation within the transaction?

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

readConcern: 'snapshot' is specifically designed for multi-document transactions. It provides a consistent snapshot of the data at the start of the transaction, ensuring that all reads within the transaction see the same data. This meets the developer's requirement for a consistent snapshot and atomicity with the write.

Why this answer

Within a multi-document transaction, the read concern must be 'snapshot' to ensure a consistent snapshot of the data for all operations in the transaction. This provides the required isolation and atomicity. Other read concerns like 'local', 'majority', or 'linearizable' do not provide the same guarantees within a transaction and may not be supported.

Exam trap

The trap here is assuming that 'majority' read concern is sufficient for transactions, but it does not provide a consistent snapshot across multiple operations.

8
MCQmedium

Refer to the exhibit. What is the most appropriate next step for an application encountering this error?

A.Display an error message to the user and stop.
B.Retry the individual failed operation only.
C.Abort the transaction and retry the entire operation.
D.Ignore the error and continue with the next request.
AnswerC

When a TransientTransactionError occurs, the correct procedure is to abort the failed transaction and execute the entire sequence of operations again. This guarantees that all changes are applied atomically, adhering to the ACID properties of the transaction and ensuring that the final state is correct and consistent.

Why this answer

The 'TransientTransactionError' label indicates that the failure occurred due to a temporary issue, such as a network hiccup or a transient server conflict. In accordance with MongoDB best practices, the application must catch this error, perform a rollback if necessary, and then retry the entire transaction from the beginning. This mechanism ensures that the application state remains consistent despite the intermittent nature of the underlying failure.

Exam trap

Candidates often attempt to fix the error by modifying specific operations within the transaction, rather than following the mandatory protocol of aborting and restarting the entire transaction.

9
MCQeasy

A developer needs to quickly inspect the contents of a collection and run ad-hoc queries against a MongoDB Atlas cluster without installing any additional software. Which tool should be used?

A.MongoDB Database Tools
B.MongoDB Compass
C.Atlas Data Explorer
D.mongosh
AnswerC

Atlas Data Explorer is a built-in web-based tool in the MongoDB Atlas UI that allows developers to browse databases, collections, and documents, and run ad-hoc queries directly from a browser. It requires no additional installation and is ideal for quick inspection. It is accessible from the Atlas dashboard under the 'Collections' tab.

Why this answer

Atlas Data Explorer is a web-based interface integrated into MongoDB Atlas that lets users view and query data without installing any software. It is the most convenient tool for quick inspection and ad-hoc queries, as it is accessible directly from the Atlas UI and requires no local setup.

Exam trap

The trap here is thinking that mongosh or Compass are always required, overlooking the built-in web tools in Atlas.

10
MCQeasy

Which MongoDB tool should be used to perform a point-in-time backup of a MongoDB cluster while the database is running?

A.mongoimport
B.mongostat
C.mongodump
D.mongorestore
AnswerC

mongodump creates a binary export of the database content. When combined with --oplog, it ensures that the backup is consistent by capturing changes that occur during the dump process. This resulting backup can be used to restore the entire database state to the exact point in time of the completion.

Why this answer

mongodump is the standard command-line utility for creating binary exports of MongoDB data. When used with the --oplog option, it allows for point-in-time recovery by capturing the operations log during the backup process. This is essential for maintaining data integrity in production environments where downtime must be avoided, allowing administrators to restore the cluster to a specific state as needed by business requirements.

Exam trap

Candidates often confuse mongodump with mongorestore or mistakenly believe it requires taking the database offline, not realizing it is designed for live cluster backups.

11
MCQhard

A developer is building an application that uses the MongoDB Node.js driver to perform a multi-document transaction. The transaction includes an update to an 'inventory' collection and an insert into an 'orders' collection. During testing, the developer notices that occasionally the transaction aborts with a TransientTransactionError. What is the most appropriate way to handle this error in the application code?

A.Restart the MongoDB server to clear the error condition.
B.Commit the transaction and ignore the error, as the changes may have been applied.
C.Immediately retry the entire transaction from the beginning.
D.Abort the transaction and return an error to the user without retrying.
AnswerC

TransientTransactionError indicates a temporary issue like a write conflict or network glitch. The recommended practice is to retry the entire transaction, as the error label suggests it may succeed on retry. The driver provides a withTransaction helper that automatically retries on TransientTransactionError, but if implementing manually, the application should catch the error and retry the whole transaction logic.

Why this answer

TransientTransactionError is a label indicating a temporary failure that may be resolved by retrying the transaction. The correct approach is to retry the entire transaction, often using the driver's built-in retry mechanism like withTransaction. Aborting without retry, committing despite the error, or restarting the server are all inappropriate responses that could lead to data inconsistency or unnecessary failures.

Exam trap

The trap here is thinking that any error during a transaction requires aborting and reporting to the user, when in fact transient errors are specifically designed to be retried automatically.

12
MCQeasy

A developer runs `mongosh` against a replica set and wants to inspect the current database's collections before writing any queries. Which command should be executed?

A.db.runCommand({ listDatabases: 1 })
B.db.collections.find()
C.show collections
D.db.getCollectionInfos()
AnswerC

In mongosh, `show collections` is a shell helper that lists all collections in the currently selected database. It maps to a listCollections command and is the quickest way to inspect schema-less structure without writing JavaScript. This matches the scenario because the developer wants a simple inventory of collections before writing queries.

Why this answer

The shell helper `show collections` is the idiomatic mongosh command for listing collections in the active database. It is concise, requires no JavaScript and directly satisfies the developer's need to inspect the database before writing queries. Other options either query a nonexistent collection, return different metadata or list databases rather than collections.

Exam trap

The trap here is confusing a shell helper that lists collection names with a method that queries documents inside a collection.

13
Multi-Selectmedium

Which TWO of the following are common use cases for using the 'mongosh' shell in a production environment?

Select 2 answers
A.Querying and troubleshooting live collection data.
B.Developing the entirety of a high-concurrency Node.js application.
C.Performing administrative tasks like index creation and collection management.
D.Replacing the driver for all production database traffic.
E.Automatically scaling the number of nodes in an Atlas cluster.
AnswersA, C

mongosh is the primary tool for executing ad-hoc queries, viewing document structures, and diagnosing data issues in production. Its ability to run standard CRUD operations and aggregation pipelines makes it the go-to tool for developers to inspect the state of the database when investigating reported bugs or inconsistencies.

Why this answer

mongosh is the modern shell for MongoDB, offering a rich environment for database administration and scripting. Beyond simple CRUD, it is essential for checking cluster health, managing indexes, and performing emergency administrative tasks directly on the server. Because it provides full access to the MongoDB driver API, it is an indispensable tool for developers and DBAs to troubleshoot production issues and perform ad-hoc data investigations effectively.

Exam trap

Candidates incorrectly select heavy application-level automation tasks or high-throughput transaction routing as primary use cases for the interactive shell.

14
MCQmedium

When using the MongoDB C#/.NET driver, which object is essential for managing the scope and lifecycle of a multi-document transaction?

A.IMongoDatabase
B.IClientSessionHandle
C.MongoClient
D.IMongoCollection
AnswerB

IClientSessionHandle is the standard interface in the C# driver for managing sessions and transactions. It allows developers to start, commit, and abort transactions safely. By passing this object into every operation, you link them to the same session, enabling the ACID properties required for multi-document operations.

Why this answer

In the .NET driver, the 'IClientSessionHandle' object is used to represent a session that controls the lifecycle of a transaction. By using the 'StartTransaction' method on this session object, developers can encapsulate multiple operations within a single, atomic unit of work. This session handle is passed to every database operation within the transaction, ensuring that all actions are associated with the correct transactional scope and are properly committed or aborted.

Exam trap

Candidates often incorrectly identify the MongoClient or Database object as the manager of transactional scope, ignoring the specific need for a session object to handle multi-document atomicity.

15
MCQhard

A developer is debugging a multi-document transaction in the MongoDB Node.js driver. The transaction updates a document in the `orders` collection and inserts into `audit`. The commit fails with a `WriteConflict` error that does not carry the `TransientTransactionError` label. What is the most appropriate action?

A.Inspect the error, resolve the conflict by re-reading or reordering operations, and retry the transaction with backoff.
B.Retry the entire transaction from the beginning.
C.Retry only the commit operation with the same transaction number.
D.Abort the transaction and report a permanent failure to the user.
AnswerA

A WriteConflict without the transient label means the conflict is deterministic at that moment, such as concurrent updates to the same document. The application should examine the error, potentially re-read the conflicting document, adjust logic and retry with backoff. This is the correct approach because it addresses the root cause rather than blindly retrying.

Why this answer

A WriteConflict that lacks the TransientTransactionError label is not automatically retryable by the driver's standard loop. The developer must inspect the error and decide how to resolve the conflict, often by re-reading the latest document version or reordering operations, then retrying with backoff. Blindly retrying the commit or the whole transaction without addressing the cause is unlikely to succeed.

Exam trap

The trap here is assuming every WriteConflict carries the TransientTransactionError label and can be retried without examining the cause.

16
MCQhard

What is the primary purpose of the 'causal consistency' feature provided by MongoDB sessions?

A.To force all reads and writes to occur on the primary node only.
B.To ensure that a client reads the results of its own writes.
C.To improve overall write throughput by batching operations.
D.To automatically shard data based on access patterns.
AnswerB

Causal consistency is specifically designed to guarantee that reads reflect the client's prior writes. Without this, a read following a write might return stale data if the read hits a secondary node that has not yet replicated the latest operation, causing confusion and potential logic errors in the application.

Why this answer

Causal consistency ensures that operations within a session appear in an order that respects the causal relationship between them, even when reading from secondary nodes. This is vital in distributed systems to prevent 'time-travel' anomalies, such as reading a stale version of a document immediately after an update. By using the operation time, MongoDB guarantees that a user sees their own writes immediately, maintaining a logical progression of data state.

Exam trap

Candidates mistake causal consistency for multi-document atomicity or ACID transactions, assuming it prevents concurrent write conflicts instead of managing read-your-own-writes ordering.

17
MCQhard

A developer uses the MongoDB Node.js driver to run a multi-document transaction that updates an accounts collection and inserts a ledger entry. The transaction commits successfully, but a second application instance immediately reads the ledger entry through a session that is not causally linked to the transaction session and receives stale data. The developer wants the second instance to observe the transaction's committed writes without changing the transaction itself. Which approach should the developer use?

A.Start a new session for the read, set readConcern to "snapshot" on the read operation, and run the read without linking it to the transaction session.
B.Use the same session that ran the transaction for the subsequent read operation on the second application instance.
C.After the transaction commits, capture the operationTime and clusterTime from the transaction session and pass them in the readConcern and afterClusterTime of the subsequent read session.
D.Set the read preference of the second instance to "primaryPreferred" and retry the read until the ledger entry appears.
AnswerC

Causal consistency in MongoDB is achieved by propagating the operationTime and clusterTime from a session that performed a causally prior operation. By including afterClusterTime in the read concern of the second session, the read waits until the cluster has advanced past the transaction's commit time, guaranteeing that the ledger entry is visible.

Why this answer

Causal consistency requires the second session's read to wait until the cluster time has passed the transaction's commit. The transaction session exposes operationTime and clusterTime, and the subsequent read must include afterClusterTime in its readConcern to enforce that ordering. This ensures the committed ledger entry is visible without modifying the transaction or relying on read preference.

Exam trap

The trap here is assuming that reading from the primary or using snapshot read concern alone guarantees visibility of a prior transaction's writes, when causal consistency actually depends on propagating the prior session's operationTime and clusterTime.

18
MCQmedium

A developer needs to create a backup of a MongoDB deployment that includes all databases and their indexes, and then restore it to a different server. The backup should be in a binary format that preserves BSON data types. Which tool should be used to create the backup?

A.mongoexport
B.mongofiles
C.mongorestore
D.mongodump
AnswerD

mongodump is the correct tool for creating a binary backup of a MongoDB deployment. It exports data in BSON format, preserving all data types, and includes index definitions. The resulting dump can be restored with mongorestore. It can back up an entire deployment or specific databases and collections, making it ideal for this scenario.

Why this answer

mongodump creates a binary backup of a MongoDB deployment, preserving BSON data types and index definitions. mongoexport produces JSON/CSV, which loses type fidelity. mongorestore is for restoring, and mongofiles is for GridFS. Thus, mongodump is the correct choice for a binary backup.

Exam trap

The trap here is confusing mongoexport with mongodump, thinking that JSON export is a suitable backup, but it loses BSON types and indexes.

19
MCQhard

A developer is using the MongoDB Node.js driver to perform a multi-document transaction that includes a read operation on a collection with a read concern of 'snapshot'. What is the effect of using 'snapshot' read concern in this transaction?

A.It provides a consistent snapshot of the data at the start of the transaction, ensuring reads see the same version of documents throughout the transaction.
B.It allows reads to see uncommitted changes from other transactions, improving performance.
C.It ensures that reads are distributed across secondary nodes for load balancing.
D.It automatically retries reads if a transient error occurs, without failing the transaction.
AnswerA

The snapshot read concern ensures that all reads within the transaction see a consistent version of the data as of the transaction start time. This prevents non-repeatable reads and provides isolation. It is the recommended read concern for multi-document transactions to avoid inconsistencies.

Why this answer

In a multi-document transaction, using snapshot read concern guarantees that all reads within the transaction see a consistent snapshot of the data as of the transaction start. This prevents anomalies such as non-repeatable reads and ensures that the transaction operates on a stable view of the data, which is critical for maintaining integrity.

Exam trap

The trap here is confusing snapshot read concern with read preference or automatic retry, when it actually provides a consistent data snapshot within the transaction.

20
MCQmedium

A developer wants to run ad-hoc queries against a MongoDB Atlas cluster from a terminal, including commands like db.collection.find() and db.adminCommand({listDatabases: 1}). The developer has the connection string and wants the least additional setup. Which tool should be used?

A.MongoDB Compass connected to the cluster
B.mongosh with the connection string passed as an argument
C.Atlas Data Federation with an S3 data source
D.mongodump with the --uri option
AnswerB

mongosh is the MongoDB Shell that connects to any deployment, including Atlas, using a standard connection string. It supports JavaScript execution, database commands, and helpers like db.collection.find(), and it requires no additional project scaffolding. Passing the connection string as an argument is the documented way to connect, making it the least-setup option for ad-hoc querying and administrative commands in a terminal.

Why this answer

mongosh is the official MongoDB Shell and is designed for interactive, terminal-based querying and administration. It connects directly with a connection string and supports both CRUD helpers and database commands, so it covers the developer's needs with minimal setup. GUI tools, backup utilities, and federation features serve different purposes and would require more configuration or would not run in a terminal.

Exam trap

The trap here is equating any MongoDB client that can connect to Atlas with a terminal shell, when only mongosh provides interactive command-line querying without extra setup.

21
MCQmedium

Which of the following describes the behavior of a 'write concern' in a MongoDB transaction?

A.Write concern is ignored inside multi-document transactions.
B.It is applied to each individual operation within the transaction.
C.It is specified during the commitTransaction command.
D.It is determined solely by the server's default configuration.
AnswerC

The write concern is explicitly set when calling commitTransaction. This allows the application to control the acknowledgement level for the entire transaction block. This mechanism is standard for ensuring that all changes are successfully hardened on the required number of nodes before the application considers the transaction finished.

Why this answer

Transactions in MongoDB honor the write concern configured on the 'commitTransaction' command. This allows developers to specify the durability level, such as 'majority', ensuring that changes are acknowledged by the majority of replica set members before the transaction is considered complete. Proper management of write concerns ensures that even if a primary node fails immediately after a commit, the data remains durable and consistent across the cluster.

Exam trap

Candidates often mistakenly believe write concern is configured globally at the client or session level, forgetting that for transactions, it must be explicitly defined within the commitTransaction command parameters.

22
MCQmedium

A developer is writing a Node.js application that must execute a series of document updates across two collections atomically. The application uses the MongoDB Node.js driver and needs to ensure that if any operation fails, all changes are rolled back. Which driver API should the developer use to achieve this?

A.Use the insertMany() method with the ordered option set to false to ensure atomicity.
B.Use the bulkWrite() method with ordered: true to group updates across collections.
C.Use the startSession() method on the MongoClient instance and then call session.withTransaction() to run the operations.
D.Use the findOneAndUpdate() method with a session parameter for each update.
AnswerC

The MongoDB Node.js driver provides startSession() to create a client session, and withTransaction() to run a multi-document transaction with automatic retry and commit/abort handling. This is the correct approach for atomic multi-collection updates in a replica set or sharded cluster, as it ensures all operations either commit together or roll back on error.

Why this answer

Multi-document transactions in MongoDB are managed through client sessions. The Node.js driver's session.withTransaction() method handles the lifecycle, including retries on transient errors and automatic commit or abort. This ensures that updates across multiple collections are atomic.

Other methods like bulkWrite or findOneAndUpdate operate on a single collection or document and lack the necessary transactional guarantees.

Exam trap

The trap here is assuming that any write method accepting a session parameter automatically participates in a transaction.

23
MCQmedium

What is the primary role of the 'mongos' process in a sharded cluster?

A.It stores the data chunks for the shards.
B.It routes requests to the correct shards.
C.It manages the election of the primary node.
D.It persists the metadata for the entire cluster.
AnswerB

mongos is the request router. It consults the config servers to understand how data is partitioned across the cluster and forwards client queries to the relevant shards. This routing functionality is critical for providing a unified view of the data to the application, hiding the sharding distribution logic.

Why this answer

The 'mongos' process acts as a query router, bridging the gap between client applications and the sharded cluster. It receives incoming requests, determines which shards contain the necessary data using the cluster's metadata, and routes the request to the appropriate shards. It then aggregates the results before returning them to the client.

This abstraction allows applications to interact with the entire cluster as if it were a single database instance.

Exam trap

Candidates often confuse the role of the 'mongos' router with the config servers or individual shards, mistakenly believing it stores the actual database data or manages consensus elections directly.

24
Multi-Selecthard

A developer is configuring an Atlas Search index on a collection of product documents. The index definition uses a dynamic mapping. Which two statements accurately describe the behavior or configuration of Atlas Search indexes in this scenario? (Choose two.)

Select 2 answers
A.Dynamic mappings index fields whose names begin with an underscore, such as _id, by default.
B.Atlas Search indexes are stored in a separate search process and are updated asynchronously from the primary replica set.
C.Atlas Search indexes can be created on any MongoDB deployment, including self-managed community servers.
D.A dynamic mapping automatically indexes all dynamically indexable field types in each document, including strings, numbers, and dates.
E.Setting dynamic to true requires also specifying analyzers for every string field in the collection.
AnswersB, D

Atlas Search uses a dedicated search process that maintains its own index separate from the MongoDB data files. Changes from the replica set are replicated to the search process and applied asynchronously, so there can be a brief delay between a write and its visibility in $search results. This architecture keeps search workloads isolated from the primary's storage engine while still reflecting changes through the oplog.

Why this answer

Dynamic mapping in Atlas Search automatically indexes supported field types without per-field declarations, and the search index itself is maintained by a separate process that receives changes asynchronously from the replica set. The other statements misstate requirements or availability: analyzers are not mandatory for every string under dynamic mapping, Atlas Search is unavailable outside Atlas, and underscore-prefixed fields like _id are not dynamically indexed.

Exam trap

The trap here is assuming dynamic mapping indexes every field including _id and requires explicit analyzers, when it actually skips certain fields and applies defaults automatically.

25
MCQmedium

In the context of the MongoDB Node.js driver, what happens if an application fails to provide a write concern?

A.The write will never be acknowledged by the server.
B.The server automatically sets the write concern to 'majority'.
C.The driver applies the default write concern (usually 'w: 1').
D.The write will be rejected by the MongoDB server.
AnswerC

By default, the MongoDB driver uses a write concern of 'w: 1'. This ensures the primary node writes the data to its journal or memory and acknowledges the request. This provides a balance between performance and immediate confirmation, suitable for general-purpose applications that do not require maximum consistency guarantees.

Why this answer

If no write concern is explicitly defined, the driver uses the default write concern configured at the client or database level. If no default is configured, the driver falls back to 'w: 1', meaning the operation is considered successful once the primary node receives and acknowledges the write. This is the standard behavior to balance performance with a baseline level of data durability in most production applications.

Exam trap

Candidates often incorrectly assume that omitting a write concern will cause the operation to fail or wait for all replicas, rather than defaulting to the standard 'w: 1' behavior.

26
MCQmedium

A developer needs to run a multi-document transaction using the MongoDB Node.js driver. The transaction must read from the 'orders' collection and write to the 'inventory' collection. Which sequence of operations correctly implements the transaction?

A.Start a session with client.startSession(), start a transaction with session.startTransaction(), perform reads and writes with the session option, then commit with session.commitTransaction().
B.Use a session, start a transaction, perform operations with the session, and rely on automatic commit when the session ends.
C.Begin a transaction with db.beginTransaction(), run operations on the db object, and call db.commitTransaction().
D.Use client.startTransaction() directly, perform operations without a session, and call transaction.commit().
AnswerA

This is the correct sequence for a multi-document transaction in the Node.js driver. You must start a session to associate operations with a transaction, begin the transaction, pass the session to each operation, and finally commit. Aborting on error is also required, but commit is the successful completion step.

Why this answer

A multi-document transaction in the Node.js driver requires a session. The session must be started, the transaction begun, operations executed with the session passed as an option, and then the transaction committed. Omitting any step, such as not passing the session to operations or not explicitly committing, results in operations not being part of the transaction or the transaction remaining open.

Exam trap

The trap here is assuming that the driver provides top-level transaction methods like client.startTransaction() instead of requiring a session-based approach.

27
MCQmedium

Which of the following describes the behavior of a 'causally consistent' session in MongoDB?

A.It forces all reads and writes to the primary node.
B.It ensures operations are observed in their logical order.
C.It eliminates the need for replication in the cluster.
D.It significantly increases the latency of every write.
AnswerB

Causal consistency guarantees that the database reflects the logical order of operations performed within the session. It ensures that 'read-your-writes' is respected across the cluster, preventing scenarios where a client might see an outdated version of data that should have already been updated by a previous write.

Why this answer

Causal consistency ensures that operations within a session reflect the order in which they were performed. If an application writes a document and then immediately reads it back within the same session, causal consistency guarantees that the read will see the result of that write, even if the read is directed to a secondary node. This is vital for applications requiring linear-like history for user interactions across distributed read/write nodes.

Exam trap

Candidates often confuse causal consistency with 'strong consistency' or 'read-your-writes' across all nodes. They fail to realize it is specific to the logical order within a session.

28
Multi-Selectmedium

An application using the MongoDB Node.js driver must ensure that a multi-document transaction is retried correctly when it encounters a transient error. Which two practices are required? (Choose two.)

Select 2 answers
A.Increase the transaction lifetime limit beyond 60 seconds to avoid all retries.
B.On a commit error with the UnknownTransactionCommitResult label, retry the commit operation.
C.Set the readConcern to 'snapshot' on every individual operation inside the transaction.
D.Disable write concern to make commits faster and reduce retries.
E.Check the error for the TransientTransactionError label and retry the entire transaction.
AnswersB, E

UnknownTransactionCommitResult means the commit outcome is unknown, so retrying the commit is safe and necessary. The driver surfaces this label, and the application should retry the commit until it succeeds or a definitive error occurs. This prevents lost writes when the commit response was not received.

Why this answer

The Node.js driver exposes error labels that tell the application how to recover. A TransientTransactionError requires restarting the entire transaction, while UnknownTransactionCommitResult requires retrying the commit. These two behaviors are the documented retry pattern for multi-document transactions.

Other options either misplace read concern, misunderstand the lifetime limit or weaken durability without addressing retries.

Exam trap

The trap here is assuming that raising limits or changing write concern can replace the driver's prescribed retry logic for transaction error labels.

29
MCQeasy

Which of the following best describes the purpose of the MongoDB 'mongosh' shell?

A.To act as a GUI for database administration.
B.To serve as a modern interactive JavaScript shell.
C.To perform background replication between nodes.
D.To automatically optimize database query indexes.
AnswerB

mongosh is a full-featured JavaScript environment that allows developers to run commands against MongoDB. It is designed to be the primary interactive shell for developers, providing enhanced usability, better autocompletion, and support for the latest MongoDB features, significantly improving the experience over the previous, deprecated 'mongo' shell.

Why this answer

The 'mongosh' shell is the modern, interactive command-line interface for MongoDB. It allows developers to run JavaScript commands to interact with the database, perform CRUD operations, manage indexes, and execute administrative tasks. It replaces the legacy 'mongo' shell, offering improved features like syntax highlighting, auto-completion, and better integration with current MongoDB server versions, making it the essential tool for daily development and database management tasks.

Exam trap

Candidates sometimes confuse mongosh with the MongoDB server process itself (mongod), failing to distinguish between the client-side interactive shell and the database server binary.

30
MCQhard

A developer is using the MongoDB Node.js driver to perform a multi-document transaction that updates multiple collections. During testing, the transaction occasionally fails with a TransientTransactionError. What is the most appropriate way to handle this error?

A.Increase the transaction lifetime limit using the maxTransactionTimeMS option and continue without retrying.
B.Retry the entire transaction from the beginning, including starting a new session and re-executing all operations.
C.Ignore the error and proceed, as MongoDB will automatically retry the transaction.
D.Retry only the failed operation within the same transaction, without aborting or restarting the transaction.
AnswerB

TransientTransactionError indicates a temporary issue such as a write conflict or network blip. The recommended approach is to retry the entire transaction, as partial retries may lead to inconsistent state. Starting a new session ensures a clean transaction context. This is the standard pattern for handling transient errors in MongoDB transactions.

Why this answer

When a transaction fails with TransientTransactionError, the correct approach is to retry the entire transaction. This means aborting the current transaction if it is still open, starting a new session or reusing the session after aborting, and re-executing all operations. Retrying only a single operation or ignoring the error can result in partial updates or constraint violations.

Exam trap

The trap here is thinking that MongoDB automatically retries transactions or that retrying a single operation is sufficient, when in fact the entire transaction must be retried.

31
MCQmedium

A developer is using the MongoDB Node.js driver to perform a multi-document transaction that updates a document in the 'orders' collection and inserts a record into the 'audit' collection. After starting the session and transaction, the update succeeds, but the insert fails due to a duplicate key error. What should the developer do to handle this error and ensure data consistency?

A.Retry the insert operation within the same transaction without aborting, hoping the duplicate key error resolves.
B.Call session.commitTransaction() to commit the successful update and ignore the failed insert.
C.Call session.abortTransaction() to roll back the update, then retry the entire transaction if appropriate.
D.Call session.endSession() to close the session and automatically roll back the transaction.
AnswerC

When an operation within a transaction fails, the transaction must be aborted to undo any changes made before the failure. Calling abortTransaction() ensures the update to 'orders' is rolled back, maintaining atomicity. After aborting, the developer can decide whether to retry the transaction, possibly after handling the duplicate key error (e.g., by checking if the audit record already exists). This is the correct way to handle errors in a transaction.

Why this answer

In a multi-document transaction, if any operation fails, the entire transaction must be aborted to maintain atomicity. The correct action is to call abortTransaction() to roll back all changes made within the transaction. Committing or ignoring the error would lead to inconsistent data.

Ending the session does not explicitly abort. Retrying without aborting is futile.

Exam trap

The trap here is thinking that a failed operation in a transaction can be retried in place, but the transaction must be aborted first.

32
MCQmedium

A developer is building a Node.js application that connects to a MongoDB replica set. The application must ensure that every read operation sees a consistent snapshot of the data, even if other clients are concurrently modifying documents. Which read concern level should be used for these reads?

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

The "snapshot" read concern returns data as it appeared at a specific point in time, providing a consistent snapshot across multiple documents. This is exactly what the application needs to avoid seeing partial updates from concurrent writes. It is available for replica sets and sharded clusters and is often used with transactions or for consistent reads.

Why this answer

The "snapshot" read concern provides a consistent snapshot of the data across multiple documents, ensuring that the application sees a stable view even with concurrent writes. Other read concerns like "local", "majority", or "available" do not offer this snapshot isolation, so they are unsuitable for the stated requirement.

Exam trap

The trap here is confusing durability guarantees (majority) with snapshot isolation, which are distinct properties.

33
MCQeasy

Which tool is primarily recommended for performing binary backups and restores of a MongoDB deployment?

A.mongosh
B.mongodump
C.Compass
D.mongostat
AnswerB

mongodump is the official binary backup tool for MongoDB. It reads data from the database and creates a BSON dump, which is efficient and preserves data types perfectly. This tool is the standard choice for performing logical, binary backups that can be easily restored using the companion mongorestore utility.

Why this answer

mongodump and mongorestore are standard utilities for creating and restoring binary backups of MongoDB databases. Unlike mongosh which is for interaction, or Compass for visualization, these tools operate directly on the BSON data representation. Understanding the correct backup utility is essential for disaster recovery and data migration, ensuring that the integrity of the data is maintained during the backup process across different MongoDB versions.

Exam trap

Candidates often confuse mongosh or Compass as backup tools, failing to recognize that binary backups require specific utilities designed for data export and import like mongodump.

34
MCQeasy

A developer needs to quickly inspect the contents of a MongoDB collection and run ad-hoc queries during development. The developer prefers a command-line interface that supports JavaScript syntax and allows direct interaction with the database. Which MongoDB tool should be used?

A.MongoDB Compass
B.mongosh
C.MongoDB Database Tools
D.MongoDB Atlas
AnswerB

mongosh is the MongoDB Shell, a command-line interface that supports JavaScript syntax and allows direct interaction with the database. It is designed for ad-hoc queries, administration, and development tasks. It meets the developer's preference for a command-line tool with JavaScript support.

Why this answer

mongosh is the official command-line shell for MongoDB, supporting JavaScript syntax and enabling direct interaction with the database for ad-hoc queries and administration. It is the appropriate tool for a developer who prefers a command-line interface. The other options are either GUI-based, cloud services, or specialized utilities not intended for interactive querying.

Exam trap

The trap here is assuming that MongoDB Compass, being a MongoDB tool, is command-line based, but it is actually a GUI.

35
MCQeasy

A developer needs to load a large JSON file into a collection named 'inventory' in the 'retail' database on a MongoDB server running on localhost. The file contains one JSON document per line. Which command-line tool should be used?

A.mongofiles --db retail --collection inventory --file inventory.json
B.mongoexport --db retail --collection inventory --file inventory.json
C.mongoimport --db retail --collection inventory --file inventory.json
D.mongorestore --db retail --collection inventory inventory.json
AnswerC

mongoimport is specifically designed to import data from JSON, CSV, or TSV files into a MongoDB collection. The --db and --collection flags specify the target database and collection, and --file points to the source file. This is the standard tool for bulk loading JSON data, and it supports one JSON document per line, which matches the scenario.

Why this answer

The correct tool is mongoimport, which is part of the MongoDB Database Tools and specifically built to import data from JSON, CSV, or TSV files into a collection. The other tools serve different purposes: mongorestore restores BSON dumps, mongoexport exports data, and mongofiles manages GridFS files. Only mongoimport matches the requirement of loading a JSON file into a collection.

Exam trap

The trap here is confusing mongoimport with mongorestore, assuming both can import JSON data, but mongorestore only works with BSON dumps.

36
MCQeasy

A developer needs to import a large JSON file into a MongoDB collection named 'products' in the 'catalog' database. The file contains one JSON document per line (JSON Lines format). Which MongoDB tool should be used to accomplish this efficiently?

A.mongoimport
B.mongorestore
C.mongodump
D.mongostat
AnswerA

mongoimport is specifically designed to import data from JSON, CSV, or TSV files into a MongoDB collection. It supports JSON Lines format by default and can handle large files efficiently. It also provides options to specify the database, collection, and field types, making it the correct tool for this task.

Why this answer

The task requires importing a JSON Lines file into a MongoDB collection. mongoimport is the designated tool for importing JSON, CSV, or TSV data. It handles JSON Lines natively and is optimized for bulk imports. The other tools serve different purposes: mongorestore is for BSON backups, mongodump is for creating backups, and mongostat is for monitoring.

Exam trap

The trap here is confusing mongorestore with mongoimport because both deal with data restoration, but only mongoimport handles JSON Lines files.

37
MCQeasy

When using MongoDB Compass to analyze query performance, which tool is most effectively used to view the explain plan output in a visual format?

A.The Aggregation Pipeline builder.
B.The Explain Plan tab.
C.The Schema validation tab.
D.The Connection health monitor.
AnswerB

The Explain Plan tab in Compass displays the execution metrics in a clear, visual format. It provides details on stage transitions, index scans, and document counts, making it the primary tool within the GUI for interpreting how the database engine processes queries and where performance issues arise.

Why this answer

MongoDB Compass provides a built-in 'Explain Plan' tab that visualizes how the database executes a query. This tool represents the execution path as a tree, highlighting which indexes were used, how many documents were scanned, and the efficiency of the operation. Using this visual output is essential for developers to identify bottlenecks, missing indexes, or suboptimal query structures without manually parsing complex JSON output from the shell.

Exam trap

Candidates sometimes confuse raw shell explain output methods with Compass features, failing to identify the dedicated visual GUI tab designed for analysis.

38
MCQeasy

A developer needs to create an Atlas Search index that supports autocomplete on a `name` field. Which Atlas Search index definition is required?

A.A text index with the default language analyzer.
B.A standard string index with dynamic mapping enabled.
C.An index with a field of type 'autocomplete' and an analyzer such as 'lucene.standard' or a custom edge-gram analyzer.
D.A wildcard index on the `name` field.
AnswerC

Atlas Search provides the `autocomplete` field type specifically for prefix-based suggestions. It requires an analyzer that generates edge-grams or n-grams, such as `lucene.standard` with edgeGram or a custom analyzer. This matches the scenario because the developer needs autocomplete on the `name` field.

Why this answer

Atlas Search uses the `autocomplete` field type to support prefix suggestions. The field must be configured with an analyzer that produces edge-grams or n-grams, such as a custom analyzer using the edgeGram tokenizer. Standard string or text indexes do not provide this behavior.

Wildcard indexes are unrelated to Atlas Search and cannot satisfy the autocomplete requirement.

Exam trap

The trap here is confusing MongoDB text indexes with Atlas Search autocomplete field types, which serve different purposes.

39
MCQmedium

An application uses a multi-document transaction to update inventory and process an order. What happens if the transaction exceeds the default transaction lifetime limit of 60 seconds?

A.The transaction automatically commits partial changes to ensure data availability.
B.The client receives a warning, but the transaction continues until completion.
C.The server automatically aborts the transaction and returns an error to the client.
D.The database increases the transaction lifetime limit dynamically to prevent failure.
AnswerC

When the transaction duration exceeds the configured limit, the server aborts it to prevent prolonged locking. The client receives an error upon the next attempt to interact with the transaction or during the commit phase, signaling that the operation failed and must be retried.

Why this answer

Transactions in MongoDB are designed to be short-lived to prevent performance degradation and memory pressure. If a transaction stays open longer than the transactionLifetimeLimitSeconds configuration, the reaper process marks it as aborted. This ensures that locking contention is minimized, as prolonged transactions hold locks on documents, preventing other operations from proceeding and potentially leading to high latency or deadlocks across the cluster.

Exam trap

Students often believe transactions can run indefinitely as long as the client stays connected, ignoring the server-enforced lifetime timeout limit.

Ready to test yourself?

Try a timed practice session using only Drivers Tools Transactions Search questions.