All 75 MongoDB quiz questions below come with a short explanation, visible right on the page — no sign-in needed. They're grouped by beginner and intermediate levels and 14 subtopics, so you can revise one part at a time. Choose Try MongoDB quiz above to take a scored run and review the questions you got wrong.
A.Tables of rows and columns with a fixed schema, exactly like PostgreSQL
B.A graph of nodes and edges, optimized for multi-hop relationship queries
C.BSON documents in collections, with no schema required up front
D.Flat key-value pairs where each value is just a string
Answer: C
MongoDB stores BSON documents in collections. BSON is the binary form of JSON, with extra types like Date, ObjectId, and Decimal128. Documents nest objects and arrays, and two documents in the same collection don't have to share the same set of fields.
A 5-million-document collection makes db.users.find({ email: "a@b.c" }) very slow. What is the most common cause?
A.String queries are always slower than numeric ones, so email must become a number
B.The email field has no index, so MongoDB must scan the whole collection
C.You must use findOne instead of find, since find always reads the whole collection
D.The collection is too large so it must be sharded, with no alternative
Answer: B
A missing index on email. Without one, MongoDB reads all 5 million documents one by one. Creating db.users.createIndex({ email: 1 }, { unique: true }) turns the lookup into a B-tree search. Confirm with .explain() — seeing COLLSCAN means no usable index.
How do updateOne({ _id: 1 }, { name: "B" }) and updateOne({ _id: 1 }, { $set: { name: "B" } }) differ?
A.The operator-less form REPLACES the whole document; $set only edits the named fields
B.The version without $set is faster because it skips operator parsing
C.The two are entirely equivalent, $set is just more verbose
D.$set only works for new fields; existing fields need $replace
Answer: A
Without a $ operator it's full-document replacement semantics — any field not listed disappears. $set only modifies the listed fields. Modern drivers reject updateOne with no operators to prevent accidental data loss; for a real replacement use replaceOne.
A.Only A — a scalar field does not match an array-style query
B.A and C — an array matches if any of its elements equals the sought value
C.No documents — you must write { tags: ["mongodb"] } to match
D.Only C — searching inside an array requires $in or $elemMatch
Answer: B
Matches A and C. For an array field, { tags: "mongodb" } matches when at least one element equals that value; this syntax also matches a scalar field. { tags: ["mongodb"] } is an exact array match — it only hits documents whose array is exactly that.
Which command tells you whether a query uses an index?
A.db.collection.stats() — it returns the last query's execution plan
B..explain("executionStats") — it shows the plan and the index used
C.db.collection.getIndexes() — it says which index a query is using
D.There is no way to know; you must time it and guess
Answer: B
db.coll.find({...}).explain("executionStats"). Read the stage (IXSCAN means an index is used, COLLSCAN means a full collection scan), the indexName, and compare totalDocsExamined with nReturned — the closer the two numbers, the more efficient the query.
B.find() reads from the primary while findOne() reads from a secondary
C.find() returns a cursor; findOne() returns one document or null
D.find() only works when an index exists while findOne() does not need one
Answer: C
find() returns a cursor — you must iterate or call toArray() to get data. findOne() returns a single document directly, or null if nothing matches. In terms of performance, findOne() is equivalent to find().limit(1).
A.Finding documents that live in another collection
B.Matching documents whose value is in a given list
C.Inserting several documents at once
D.Checking whether a field exists in the document
Answer: B
$in matches when the field's value equals any element of the given array: { status: { $in: ["paid", "shipped"] } }. For an array field, it matches when at least one element is shared. $nin is the negation.
B.12 bytes, containing the document's creation timestamp
C.It is the SHA-256 hash of the document's content
D.It is an incrementing integer allocated sequentially by the server
Answer: B
ObjectId is 12 bytes: 4 bytes of second-precision timestamp, 5 bytes of per-process randomness, and a 3-byte counter. Since the timestamp comes first, it increases over creation time, and you can extract the creation date without an extra createdAt field.
What should you use to insert 1000 documents at once?
A.insertMany() — send the whole batch in few network round trips
B.A loop calling insertOne() 1000 times, since MongoDB batches them itself
C.Repeated calls to replaceOne()
D.updateMany() with upsert: true
Answer: A
insertMany(). It wraps many documents into fewer network round trips, so it's much faster than a loop of insertOne. By default it runs ordered (ordered: true) — it stops on error; set ordered: false to skip failing records and keep inserting the rest.
db.collection.getIndexes() lists every index with its definition. To see which index is actually used, add db.collection.aggregate([{ $indexStats: {} }]) — it gives the usage count of each index.
What problem do limit() and skip() have for deep pagination?
A.They still have to walk past every skipped document
B.They cannot be combined with sorting
C.They only work on collections under a million documents
D.Results come back in the wrong order when there is no index
Answer: A
The database must still walk through every skipped document before reaching the wanted page. So page one thousand is far slower than the first page, even though the number of returned results is the same.
What happens when inserting into a collection that does not exist?
A.Lazily on access, plus a background sampling process
B.Immediately at the moment the expiry time passes
C.When the client next runs a scan
D.Only when memory runs out
Answer: A
The collection is created automatically, and so is the database if it doesn't exist yet. MongoDB creates them right at the first write operation, so no prior declaration is needed.
Which fields does find({}, { name: 1, email: 1 }) return?
A.allkeys-random, evicting a random key
B.noeviction, returning an error when memory is full
C.volatile-lru, only evicting keys that have an expiry
D.allkeys-lru, evicting the least recently used key
Answer: D
name, email and _id. The identifier field is always returned unless explicitly excluded by setting a value of 0 for it. To drop it, you must state it explicitly in the projection.
A.A single command combining set-if-absent with an expiry
B.Set the key first, then set the expiry
C.Check whether the key exists and then set it
D.Use a list and take an element as the lock
Answer: A
Both: documents that have that field with a null value, and documents that don't have the field at all. To distinguish them, use the field existence operator instead of comparing to null.
What type should store a record creation timestamp?
A.Delete the key directly
B.A Lua script or a transaction so the check and delete are atomic
C.Overwrite the key with an empty value
D.Set the key's expiry to zero
Answer: B
A BSON date/time type. Only this type compares and sorts correctly by time, works with date operators in aggregation, and supports a TTL index that auto-expires documents.
Creating a unique index on email when two duplicate emails already exist. Result?
A.The snapshot is only for replication while the log is only for backups
B.The log is faster to restore than the snapshot
C.The snapshot is stored in memory while the log is on disk
D.The snapshot is periodic while the log records every command
Answer: D
The index creation command fails. An index cannot be created when existing data violates the constraint, so you must find and handle the duplicate records first — usually by aggregating with a group on that field and filtering groups with more than one.
How does countDocuments() differ from estimatedDocumentCount()?
A.The cache slows down because too many keys are checked
B.Memory is exhausted because too many keys expire together
C.Many clients rebuild the same key at once when it expires
D.The cache returns wrong data after expiry
Answer: C
One command counts exactly according to a condition so it has to scan data; the other reads metadata stats so it returns almost instantly but takes no filter condition and can drift after an incident.
C.Take a rebuild lock, or refresh proactively before expiry
D.Increase the number of cache nodes
Answer: C
Dropping the collection removes the index definitions too and returns the space immediately. Deleting documents keeps the collection and its indexes, runs much slower on large data, but supports filter conditions.
How does a mongodb+srv:// connection string differ from mongodb://?
A.A string counter with an expiry
B.A hash keyed by minute
C.A sorted set scored by timestamp
D.A list holding each request
Answer: C
The server list is resolved via DNS records instead of being listed manually. You only need a single domain name, and default options also come from DNS — so adding or removing servers in the cluster doesn't force changes to the app configuration.
How does $exists: false differ from comparing to null?
A.A stream, which retains messages and supports consumer groups
B.A list used as a queue
C.Publish/subscribe with several subscribers
D.A sorted set scored by priority
Answer: A
It only matches documents that completely lack the field, while comparing to null matches both fields with a null value and missing fields. This is the only way to distinguish the two situations.
When should related data be embedded in a document rather than referenced in another collection?
A.Always embed — MongoDB has no joins so referencing is pointless
B.When the number of children is unbounded, such as all of a device's logs
C.When the child data is always read together with the parent and is bounded in size
D.When the child data is shared by many parent documents, to avoid duplication
Answer: C
Embed when the child data is always read with the parent, has a bounded count, and isn't queried on its own. Reference when the data is shared across many places, when the array can grow without bound, or when it needs independent queries. Hard limit: a document is at most 16MB.
A.A — using one field out of a two-field index makes the index useless
B.C — a compound index can only be used with a leftmost prefix
C.All three work, since MongoDB reorders the index fields as needed
D.B — a range query ($gt) cannot use an index
Answer: B
C can't use it. A compound index only serves queries matching a left prefix: {status} or {status, createdAt}. Filtering on createdAt alone matches no prefix, so it has to scan. If you need queries on createdAt alone, add a separate index for it.
A.It counts the users with paid orders without summing money
B.It fetches the 10 highest-value orders in the whole collection
C.It deletes unpaid orders and returns the 10 remaining ones
D.It groups paid orders per user and takes the top 10 biggest spenders
Answer: D
It computes the top 10 highest-spending users: $match filters paid orders, $group groups by userId summing the amount and counting orders, $sort orders by total descending, $limit takes 10. Each stage takes the previous stage's output.
A.Yes — a single document is always atomic, and multi-document transactions arrived in 4.0
B.Yes, and it should be used for every write to keep the data safe
C.No — MongoDB is NoSQL so it fundamentally cannot be ACID
D.Yes, but only within a single collection, never across collections
Answer: A
Yes. Writes to a single document are always atomic — even when updating multiple nested fields. Multi-document transactions exist since 4.0 (replica set) and 4.2 (sharded cluster). But transactions are expensive, so modeling so a business operation fits in one document is still the preferred approach.
Which two different problems do replica sets and sharding solve?
A.Replica sets are for redundancy; sharding is for horizontal scale
B.Both replicate data, differing only in the number of copies
C.Sharding replaced replica sets in MongoDB 5.0
D.Replica sets speed up writes while sharding speeds up reads
Answer: A
Replica set = multiple copies of the same data, giving high availability and automatic failover when the primary dies. Sharding = splitting data by shard key across many nodes, giving scalability beyond a single machine. In practice each shard is itself a replica set.
What is $lookup equivalent to in SQL, and what should you watch out for?
A.MongoDB has no joins; $lookup merely renames fields
B.It merges two collections into a new collection stored on disk
C.Close to a LEFT OUTER JOIN — it attaches an array of matching documents; index the joined field
D.Equivalent to an INNER JOIN — documents with no match are dropped from the result
Answer: C
$lookup is like a LEFT OUTER JOIN: each document gets an array of matched documents from the other collection, empty if none match. Always index the joined field (foreignField), otherwise every input document triggers a full scan of the other collection.
You need expired sessions removed automatically after 24 hours. What built-in mechanism does MongoDB provide?
A.A TTL index — an index on a date field with expireAfterSeconds
B.Set maxAge in the collection's schema at creation time
C.Use a capped collection, which removes old documents by age
D.Nothing built in — you must write a cron job calling deleteMany periodically
Answer: A
A TTL index: db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 86400 }). A background process runs roughly every 60 seconds and deletes documents whose createdAt has expired. The indexed field must be a date type, and deletion is not instantaneous at the exact expiry second.
Only 3% of documents have a deletedAt field. Which index type indexes it while saving space?
A.A compound index on deletedAt and _id
B.A hashed index
C.A text index — optimized for sparsely present fields
D.A partial index — indexing only the documents matching a condition
Answer: D
A partial index: createIndex({ deletedAt: 1 }, { partialFilterExpression: { deletedAt: { $exists: true } } }). It only contains those 3% of documents, so it's small and fast to write. In return, queries can only use this index when the filter condition covers the index's condition.
How do you make the database reject documents missing required fields, given MongoDB enforces no schema?
A.Schema validation with $jsonSchema declared on the collection
B.There is no way — validation must happen entirely in the application
C.Set strict: true when connecting the driver
D.Create a unique index on every required field
Answer: A
Schema validation with $jsonSchema: declare required and data types on the collection, and MongoDB rejects writes that violate. It supplements rather than replaces application-side checks — but it's a final safety net when many services write to the same collection.
Setting readPreference: "secondary" offloads the primary. What is the trade-off?
A.Indexes are unusable on a secondary
B.There is no trade-off, so it should always be enabled for performance
C.Queries run slower because secondaries have weaker hardware
D.You may read stale data because of replication lag
Answer: D
Reading from a secondary can return stale data because replication has latency. A common scenario: a user saves a change, the page reloads, reads from a secondary and shows old data. So choose read preference per query, don't enable it broadly.
In aggregation, how do $project and $addFields differ?
A.$addFields can only be used at the end of a pipeline
B.$project only renames fields and cannot compute
C.$project keeps only the listed fields; $addFields keeps everything
D.The two are identical, $addFields is just the newer name
Answer: C
$project is a whitelist — anything not listed is dropped. $addFields (and its alias $set) only adds, keeping the rest. When you just need to add a computed field without re-listing everything, use $addFields.
A.One assigns a value, the other removes the field from the document entirely
B.One edits an existing document, the other creates a new one
C.One applies to top-level fields, the other to nested ones
D.One runs synchronously and the other in the background
Answer: A
One assigns a value to the field, the other removes the field from the document entirely. Removing is different from assigning an empty value: queries that check for the field's existence return different results between the two.
A.It updates every matching document instead of just one
B.It creates a new document when no matching document is found
C.It replaces the whole document instead of just the named fields
D.It skips the operation when the document already exists
Answer: B
It creates a new document when no document matches the condition. Its biggest advantage is that it's atomic — avoiding the race of a check-then-insert done as two separate steps.
How does the query { "address.city": "HCM" } work with a nested document?
A.It reaches a nested field through a dot path and can use an index
B.It cannot use an index so it always scans the collection
C.It only works when the nested field is one level deep
D.It looks for a document with a field literally named that string
Answer: A
It accesses the nested field using dot-path notation, and it can be indexed on that path. This differs from matching the whole sub-object, which requires an exact match of everything including field order.
A.Adding an element only when it is not already in the array
B.Replacing the entire array with a new one
C.Adding several elements and capping the array's length in one operation
D.Inserting an element at an arbitrary position in the array
Answer: C
Add multiple elements at once and cap the array length in a single operation. That keeps a list of the most recent items — notifications, view history — without reading, trimming, and writing back in three separate steps.
Does stage order matter in an aggregation pipeline?
A.It only matters when the pipeline has more than five stages
B.Yes — putting $match earliest reduces the data flowing through the later stages
C.No — the optimizer reorders the stages optimally by itself
D.It only matters for stages that write data
Answer: B
Very important. Put the filtering stage as early as possible to reduce the amount of data flowing through later stages. And filtering at the start of the pipeline can use an index, whereas placing it after a transformation stage cannot.
What does $unwind do to a document with a 5-element array?
A.It removes the array and keeps the remaining fields
B.It sorts the array's elements
C.It joins the 5 elements into a single string
D.It splits it into 5 documents, each holding one element
Answer: D
It splits it into five separate documents, each keeping the other fields and holding one element of the array. Since it increases the document count, place it after the filtering stage so you don't duplicate data you don't need.
A single document aggregating the entire input. This is how you compute totals, averages, max values, or counts over the whole result set — rather than per group as when the group key is a field.
Which queries does the index { a: 1, b: 1, c: 1 } support?
A.Queries using an index prefix
B.Only queries using all three fields
C.Every combination of the three fields regardless of order
D.Only queries using the first field
Answer: A
Queries that use a prefix of the index: the first field, the first two fields, or all three. A query using only the second or third field has no prefix, so it cannot take advantage of it.
What must be considered when creating an index on a large production collection?
A.The application must be stopped for the whole index build
B.Indexes can only be created on collections under a million documents
C.Since version 4.2, index builds no longer block writes as they used to
D.The index only takes effect after restarting the server
Answer: C
Since version 4.2, index creation uses a mechanism that does not block writes for most of the time, locking only briefly at the start and end. Older versions had a separate background flag, which no longer has any meaning.
How is a many-to-many relationship usually modelled in MongoDB?
A.MongoDB does not support many-to-many relationships
B.An intermediate collection like a SQL join table
C.An array of references on one or both sides, depending on the query direction
D.Embedding both sides' full data into each other
Answer: C
An array of references on one side, or on both sides if you need to query in both directions. The decision is based on which queries run most often, not on normalization rules like in a relational database.
A.When writing several fields of one document at once
B.When you need consistent reads from one collection
C.When you need an atomic write across several documents or collections
D.When you need to guarantee the write succeeded on every replica
Answer: C
When you need atomic writes across multiple documents or multiple collections. A write to a single document is already atomic, so a transaction is unnecessary in that case — and it is significantly more expensive.
What are the consequences of a poor shard key choice?
A.Data and load pile onto one shard, forfeiting the point of splitting
B.Queries return wrong results because the data is distributed
C.Writes stop working entirely
D.Other fields can no longer be indexed
Answer: A
Data and load pile up on one shard, losing all the benefit of sharding. The classic example is a monotonically increasing key: every new write lands on the same shard at the end of the value range.
A.The set of collections open in the current session
B.The frequently accessed data and indexes, which should fit in RAM
C.The number of active connections to the database
D.The total size of the whole database on disk
Answer: B
The portion of data and indexes that is accessed frequently. The most important operational rule is that this portion must fit in memory — if it exceeds it, every query has to read from disk and latency rises by tens of times.
C.Measuring how much disk space each collection occupies
D.Recording slow operations to find queries needing optimization
Answer: D
It records operations slower than a threshold to find queries that need optimization. It writes to a capped collection inside the same database, so queries and analysis work with familiar commands.
What constraints apply to the _id field in MongoDB?
A.Required, unique, immutable, and automatically indexed
B.It may repeat as long as it is in different collections
C.It must be an ObjectId generated by MongoDB
D.It can be changed after the document is created
Answer: A
It is mandatory, unique within a collection, immutable once created, and always indexed. It accepts any type except arrays, so strings or numbers work as keys — it is not required to be the default identifier type.
How does $lookup with a sub-pipeline (since 3.6) improve on the basic form?
A.It runs faster because it uses indexes better
B.It allows filtering and transforming on the joined collection
C.It returns a single document instead of an array
D.It allows joining a collection in another database
Answer: B
It allows filtering and transforming on the joined collection before results are merged. The basic form only matches fields for equality, so it has to pull back all matching documents and filter them in a later stage.
A.A secondary becomes the primary automatically and instantly
B.The remaining nodes elect a new primary, with a few seconds of no writes
C.All the data is lost and must be restored from backup
D.The cluster goes read-only until someone intervenes
Answer: B
The remaining nodes hold an election and pick a new primary, usually within seconds — writes are unavailable during that window. The condition is that a majority of the replica set's voting members are available, so a two-voting-member cluster that loses one node cannot elect.
A.The server's error log used for diagnosing incidents
B.A log of write operations that secondaries read to stay in sync
C.A write buffer holding data before it reaches disk
D.An automatic backup created on a schedule
Answer: B
A collection recording every write operation on the primary so secondaries can read and replay them. It is size-capped — a node that falls too far behind cannot catch up and must resync from scratch.
A.A separate collection the application writes into
B.Periodic polling performed by the driver
C.Triggers defined on each collection
D.The replica set's oplog — requires a replica set
Answer: D
The replication log of the cluster — so it only works on a replica set or sharded cluster, not on a standalone node. Because it builds on an existing log, the application needs no extra writes and no periodic polling.
How should the MongoDB driver connection pool be configured?
A.One shared client for the whole application, not a new one per request
B.Set the pool size as large as possible so nothing ever waits
C.Create a new client per request and close it afterwards
D.Disable the pool and use a direct connection per query
Answer: A
Create one shared client object for the whole application and reuse it. That object manages its own connection pool internally — creating a new one per request opens many excess connections and quickly exhausts the server's limits.
How should a document structure change be handled on a live collection?
A.Nothing is needed because MongoDB has no schema
B.Run one bulk update across the whole collection immediately
C.Create a new collection and copy all the data across
D.The application reads both shapes, then migrates gradually on write
Answer: D
First make the application read both shapes, then migrate gradually as each document is written. Bulk updates on a large collection are resource-heavy and hard to roll back when problems appear.
B.Constraints declared in the index creation command itself
C.A JSON Schema attached to the collection
D.A separate type definition file in a MongoDB-specific format
Answer: C
A widely used open standard schema, attached to the collection at creation time or via a modification command. It can declare required fields, data types, value ranges and string patterns — and it has a warn-only mode instead of rejecting.
A.A text index is basic; Atlas Search is Lucene-based and far more capable
B.A text index is faster because it runs inside the server itself
C.The two are equivalent, differing only in name
D.Atlas Search only works with English data
Answer: A
The built-in text index is fairly basic: only one such index per collection, little customization, and simple ranking. The cloud platform's search service is based on a full-featured search engine and is much more powerful.
Which backup approach should MongoDB use in production?
A.Run a scheduled export of the data to JSON
B.Copy the data directory while the server is running
C.Rely on the replica set, since the data is already copied
D.Storage-layer snapshots or a continuous backup service
Answer: D
Snapshots at the storage layer, or the platform's continuous backup service. The most important point to remember: a replica is not a backup — an accidental delete command is replicated to every node within milliseconds.
What is the minimum security setup for MongoDB in production?
A.Just set a strong password for the admin account
B.Enable authentication, restrict the listening address, and encrypt the transport
C.Just run it behind the cloud provider's firewall
D.Nothing is needed because MongoDB is secure by default
Answer: B
Three minimum things: enable authentication and authorization, restrict listening addresses instead of every interface, and encrypt traffic in transit. Many major data breaches come from instances left open to the Internet without a password.
How is bulkWrite better than issuing separate commands?
A.It sends many operations in one network round trip, cutting total latency
B.The operations are retried automatically on failure
C.It skips constraint checking to run faster
D.The operations are performed atomically like a transaction
Answer: A
It sends many operations in a single network round trip instead of one per operation. With thousands of operations, network round-trip cost dominates the time rather than the writes themselves.
It returns the document itself, and you can choose the version before or after the update via an option. This lets you get the new value in the same atomic operation, rather than reading again in a separate step that could see data already changed by someone else.
A.Move the document into a separate archive collection
B.Set the _id field to null to mark it as deleted
C.Use MongoDB's built-in option for this
D.A marker field plus a partial index, with the filtering centralized in the data access layer
Answer: D
A marker field — usually a deletion timestamp — plus a partial index covering only active documents. And most importantly: funnel the filtering into a single place at the data access layer.
How does an index on an array field (multikey index) work?
A.It stores the whole array as a single value
B.It creates one index entry per array element
C.Arrays cannot be indexed; they must be split into their own collection
D.It only indexes the array's first element
Answer: B
It creates one index entry per element of the array. This makes lookups by a specific element very fast, at the cost of a much larger index — an array of a hundred elements creates a hundred entries for one document.
An explain() result shows COLLSCAN. What does it mean?
A.The query was rejected for lack of permission on the collection
B.The query used an index and scanned in index order
C.The query scanned the whole collection because no index could be used
D.The collection is locked by another operation
Answer: C
The query has to scan the whole collection because no index can be used. That's acceptable for a small collection, but it doesn't scale — time grows linearly with the number of documents.
Which type should store monetary values in MongoDB?
A.The double type because it is JavaScript's default for numbers
B.The int32 type because money is always a whole number
C.A string type for absolute precision
D.Decimal128 or an integer in the smallest unit, never a double
Answer: D
The exact decimal type available since version 3.4, or integers counted in the smallest unit. JavaScript's default floating-point type has representation error, so the total drifts over many additions.
What problem does calling MongoDB inside a for loop from Node.js cause?
A.The connection closes after each query so it must be reopened
B.One round trip per iteration — batch it with a single query or bulkWrite
C.MongoDB rejects queries sent too rapidly in succession
D.The results come back out of order relative to the calls
Answer: B
Each loop iteration is a network trip. With a thousand elements that's a thousand round trips, and they consume nearly all the time. Collapse it into one query with a list operator, or a bulk write.
What are the trade-offs of using an ODM such as Mongoose?
A.It fully removes the need for indexes and query optimization
B.A schema and validation at the application layer, at the cost of another abstraction
C.It is mandatory because the raw driver is too complex
D.It removes the ability to use the aggregation pipeline
Answer: B
It gives you schema and validation at the application layer, plus conveniences like virtual fields and lifecycle hooks. The trade-off is an extra abstraction layer that can hide the actual query, making optimization harder when you can't tell what it generates.
What is the risk of reading from a secondary to offload the primary?
A.It increases the primary's load instead of reducing it
B.The data may be stale because replication has lag
C.Queries on a secondary cannot use indexes
D.Secondaries do not allow reads under any circumstances
Answer: B
The data may be stale because replication has lag. Writing and immediately reading back may not show the change you just wrote — a class of bug that's hard to reproduce because it depends on timing and system load.
A.Embedded arrays must not grow unbounded; they have to be split out as they grow
B.The limit is adjustable in the server configuration
C.It only matters when storing binary files in a document
D.It has no effect because no document is ever that large
Answer: A
It means embedded arrays can't grow without bound. A post document embedding all its comments will hit the limit over time, and then every write fails — fixing it at that point is very expensive.
Does { name: { $regex: "nguyen" } } use an index on name?
A.It only works on the primary node
B.It returns an incomplete result on a large keyspace
C.It changes the keys' expiry times
D.It blocks the server because it walks every key
Answer: D
No, unless the pattern is anchored to the start of the string and case-insensitivity is disabled. The index is ordered by value from the start of the string, so searching for a substring in the middle forces a full scan.
In what order should fields be arranged in a compound index?
A.Read the counter and then write the new value
B.A single command that increments and reads in one step
C.Store the request count in a list and measure its length
D.Store the count in the application's memory
Answer: B
Order: equality fields first, then the sort field, and range conditions last. Putting a range condition before the sort field forces MongoDB to re-sort in memory instead of reading in the existing order.
What problem does sorting by an unindexed field cause on a large collection?
A.A pipeline sending several commands in one round trip
B.Store the data in fewer, larger keys
C.Open several connections and send in parallel
D.Use a transaction wrapping the commands
Answer: A
The sort happens in memory, and MongoDB limits the memory allowed for each such operation. Exceeding the limit makes the query fail outright rather than just run slowly — so the error appears suddenly as data grows.
Case-insensitive name search that still uses an index — how?
A.It is guaranteed as long as the expiry is long enough
B.It is not fully guaranteed because a failover can lose writes
C.It is guaranteed once several nodes are running
D.It is guaranteed because the write is atomic
Answer: B
Create an index with a case-insensitive collation, then query with that same collation. A simpler alternative is to store an extra lowercased field and index that field.
Comparing two fields of the same document, e.g. spent > budget. What do you use?
A.The key is split across nodes so the data still fits in memory
B.Splitting the data automatically increases availability
C.A partitioned dataset can be queried across nodes in one command
D.Each node holds a full copy so reads are faster
Answer: A
Use the operator that lets you embed aggregation expressions in a query condition. Ordinary syntax only compares a field to a constant, while this operator lets you reference another field in the same document.
Incrementing a view counter: read-then-write, or $inc?
A.Query the source directly and cache the result on first request
B.Copy the whole dataset into the cache and never expire it
C.Increase the source database's timeout
D.Cache the data with a short expiry and refresh it in the background
Answer: D
Use the increment operator, because it is atomic at the document level. Read-then-write has a gap between the two steps, so two concurrent requests can both read the old value and one increment is lost.
A query uses $or on two different fields. Which index helps?
A.Read from the database and compare against the cache on every request
B.Delete or update the cache when the data changes, rather than relying on expiry
C.Set a very short expiry so the data is always fresh
D.Write to the cache and the database at the same time
Answer: B
Each branch needs its own index. MongoDB runs each branch independently, then merges and deduplicates the results, so if even one branch lacks an index the whole query must scan the entire collection.
An aggregation needs the 10 newest records. How to place $sort and $limit?
A.Split it into several string keys
B.Compress the value before writing
C.Increase the maximum value size in the configuration
D.Store the value in a hash and only edit the changed fields
Answer: D
Place them adjacent, sort first then limit. When the two stages are next to each other, MongoDB only keeps the needed number of records during the sort instead of sorting everything and then cutting — this also avoids the memory limit.
What do retryable writes do in the MongoDB driver?
A.The cache hit ratio alone
B.The key count and the memory usage per key pattern
C.The number of connected clients
D.The commands-per-second rate
Answer: B
The driver automatically retries once on a transient network error or when the cluster is switching primary. Each operation carries an identifier so the server recognizes the retry and does not apply it twice.