First 50 of 200 questions. Each one lists the choices, the correct answer, and an explanation. The checker at the top of this page saves progress in this browser when it is available.
Continue in the practice tool above to load more questions, 50 at a time.
Question 1Core MongoDB functionality (shared across all language versions)
A collection named orders contains documents with fields customerId, total, and status. Which query returns only the documents where status equals "shipped" and total is greater than 100?
- db.orders.find({ status: "shipped" }).filter({ total: { $gt: 100 } })
- db.orders.find({ status: "shipped", total: 100 })
- db.orders.find({ status: "shipped", total: { $gt: 100 } }) Correct answer.
- db.orders.find({ $or: [{ status: "shipped" }, { total: { $gt: 100 } }] })
Explanation
Fields listed in the same query document are combined with an implicit logical AND, and the $gt operator expresses a strict greater-than comparison. Writing both conditions in one filter document therefore matches only shipped orders with total above 100.
Question 2Core MongoDB functionality (shared across all language versions)
Which MongoDB shell command lists every collection in the currently selected database?
- db.getCollectionNames().count()
- db.collections()
- show collections Correct answer.
- db.stats()
Explanation
The shell helper show collections prints the names of all collections in the current database. The equivalent programmatic call is db.getCollectionNames(), which returns an array rather than a formatted list.
Question 3Core MongoDB functionality (shared across all language versions)
A document stores a field tags whose value is the array ["red", "green", "blue"]. Which query matches that document?
- db.items.find({ tags: "green" }) Correct answer.
- db.items.find({ tags: { $size: "green" } })
- db.items.find({ tags: { $in: ["green"] } })
- db.items.find({ tags: { $all: ["red", "green", "blue"] } })
Explanation
When a field holds an array, an equality match on a single scalar matches documents whose array contains that value. So { tags: "green" } selects documents where green is one of the array elements.
Question 4Core MongoDB functionality (shared across all language versions)
Which insert command adds several documents to a collection in a single call in the MongoDB shell?
- db.users.insertOne([{ name: "Ana" }, { name: "Bo" }])
- db.users.save([{ name: "Ana" }, { name: "Bo" }])
- db.users.bulkInsert({ name: "Ana" }, { name: "Bo" })
- db.users.insertMany([{ name: "Ana" }, { name: "Bo" }]) Correct answer.
Explanation
insertMany accepts an array of documents and writes them in one call, returning insertedIds for each. insertOne accepts only a single document object.
Question 5Core MongoDB functionality (shared across all language versions)
A collection has documents with an embedded object address containing city and zip. Which query matches documents where address.city equals "Oslo"?
- db.people.find({ "address.city": "Oslo" }) Correct answer.
- db.people.find({ address.city: "Oslo" })
- db.people.find({ address: { city: "Oslo" } })
- db.people.find({ $address.city: "Oslo" })
Explanation
Dot notation inside a quoted field name navigates into embedded documents. The quoted "address.city" path matches on the nested value without requiring the whole subdocument to match.
Question 6Core MongoDB functionality (shared across all language versions)
Which update operator increments a numeric field by a given amount without replacing the rest of the document?
- db.counters.updateOne({ _id: 1 }, { hits: 1 })
- db.counters.updateOne({ _id: 1 }, { $inc: { hits: 1 } }) Correct answer.
- db.counters.replaceOne({ _id: 1 }, { hits: 1 })
- db.counters.updateOne({ _id: 1 }, { $set: { hits: 1 } })
Explanation
$inc adds the specified value to the field, creating it if absent, and leaves all other fields untouched. This is the atomic way to bump a counter.
Question 7Core MongoDB functionality (shared across all language versions)
What does the projection { title: 1, _id: 0 } do in a find call?
- Returns only title, excluding the _id field. Correct answer.
- Sorts the results by title and removes _id.
- Returns only title and _id, dropping all other fields.
- Returns every field except title and _id.
Explanation
In a projection, 1 includes a field and 0 excludes it. Because _id is included by default, explicitly setting _id to 0 removes it while title remains the only returned field.
Question 8Core MongoDB functionality (shared across all language versions)
Which aggregation stage groups input documents by a field and computes a count per group?
- db.sales.aggregate([{ $group: { _id: "$region", count: { $sum: 1 } } }]) Correct answer.
- db.sales.aggregate([{ $project: { region: 1 } }])
- db.sales.aggregate([{ $sort: { region: 1 } }])
- db.sales.aggregate([{ $match: { region: 1 } }])
Explanation
$group uses the _id expression as the grouping key, and accumulator expressions such as $sum: 1 count the documents in each group. This produces one output document per distinct region.
Question 9Core MongoDB functionality (shared across all language versions)
A query on a collection with a compound index { status: 1, createdAt: -1 } filters only on createdAt. How does the index behave for this query?
- It is used as a covered index returning all fields.
- It cannot be used at all because the leading field is missing from the filter. Correct answer.
- It fully supports the query because createdAt is indexed.
- It forces the query planner to scan the collection instead of the index.
Explanation
A compound index is ordered first by its leading field, so queries that omit that prefix cannot use the index efficiently for filtering. The planner generally falls back to a collection scan or a different index.
Question 10Core MongoDB functionality (shared across all language versions)
Which statement about the _id field is accurate for a normal collection?
- It must be an ObjectId generated by the server.
- It is optional and may be omitted from every document.
- It can be duplicated across documents as long as values differ in type.
- It is unique per collection and is created automatically if omitted. Correct answer.
Explanation
Every document requires an _id, and if the client does not supply one the driver or server generates an ObjectId. A unique index on _id enforces uniqueness within the collection.
Question 11Core MongoDB functionality (shared across all language versions)
An update uses { $push: { tags: "new" } } on a field that does not yet exist. What is the result?
- The document is replaced with only the tags field.
- The update fails because $push requires an existing array.
- The field is created as an array containing "new". Correct answer.
- The field is created as the string "new".
Explanation
$push adds a value to an array field and, when the field is missing, creates it as a new array containing that value. No error occurs for an absent field.
Question 12Core MongoDB functionality (shared across all language versions)
Which query uses a regular expression to match documents whose name field starts with "Al"?
- db.people.find({ name: /Al$/ })
- db.people.find({ name: /^Al/ }) Correct answer.
- db.people.find({ name: { $eq: /Al/ } })
- db.people.find({ name: { $regex: "Al" } })
Explanation
The ^ anchor in a regular expression matches the beginning of the string, so /^Al/ selects names beginning with Al. The $ anchor instead matches the end of the string.
Question 13Core MongoDB functionality (shared across all language versions)
A query sorts on a field that has no index and returns a large result set. What is the primary performance consequence?
- The sort causes the collection to be locked for the duration of the query.
- The sort is silently ignored and documents are returned in insertion order.
- MongoDB builds a temporary index automatically for the sort.
- The sort is performed in memory and may fail if it exceeds the memory limit. Correct answer.
Explanation
Without an index that supports the sort order, MongoDB performs an in-memory sort. If the sort exceeds the configured memory limit, the operation fails unless allowDiskUse is enabled in the aggregation context.
Question 14Core MongoDB functionality (shared across all language versions)
Which aggregation stage filters documents before grouping to reduce the number of documents entering $group?
- $match Correct answer.
- $out
- $project
- $limit
Explanation
$match filters documents using query syntax and is typically placed before $group so that fewer documents are grouped. Placing it first also lets the planner use indexes.
Question 15Core MongoDB functionality (shared across all language versions)
What does the $unwind stage do in an aggregation pipeline?
- It removes duplicate documents from the pipeline.
- It reverses the order of documents in the pipeline.
- It merges two collections into a single result stream.
- It flattens an array field so that each element becomes its own output document. Correct answer.
Explanation
$unwind deconstructs an array field, emitting one document per array element. This is commonly used before $group to aggregate over individual array entries.
Question 16Core MongoDB functionality (shared across all language versions)
A developer wants an upsert that creates a document when no match exists. Which option on updateOne accomplishes this?
- db.users.updateOne({ email: "[email protected]" }, { $set: { active: true } }, { multi: true })
- db.users.updateOne({ email: "[email protected]" }, { $set: { active: true } }, { upsert: true }) Correct answer.
- db.users.updateOne({ email: "[email protected]" }, { $set: { active: true } }, { create: true })
- db.users.updateOne({ email: "[email protected]" }, { $set: { active: true } }, { insert: true })
Explanation
The upsert option tells the update to insert a new document built from the filter equality values plus the update operators when no document matches. It reports upsertedId in the result.
Question 17Core MongoDB functionality (shared across all language versions)
Which read concern level guarantees that data returned has been acknowledged by a majority of replica set members?
- linearizable
- majority Correct answer.
- local
- available
Explanation
Read concern majority returns data that has been acknowledged by a majority of the replica set members. This prevents reading data that could later be rolled back.
Question 18Core MongoDB functionality (shared across all language versions)
A document contains the field scores: [10, 20, 30]. Which query matches documents where the scores array has exactly three elements?
- db.games.find({ scores: { $exists: 3 } })
- db.games.find({ scores: { $size: 3 } }) Correct answer.
- db.games.find({ scores: { $count: 3 } })
- db.games.find({ scores: { $length: 3 } })
Explanation
$size matches arrays with exactly the specified number of elements. It requires an integer argument and cannot be combined with range operators.
Question 19Core MongoDB functionality (shared across all language versions)
Which statement about the $setOnInsert update operator is correct?
- It is only valid together with $unset.
- It removes fields when a document is inserted.
- It applies field values only when an upsert results in a new document. Correct answer.
- It sets fields on every update regardless of whether an insert occurred.
Explanation
$setOnInsert assigns values only when an upsert inserts a new document. On updates to existing documents, the operator has no effect.
Question 20Core MongoDB functionality (shared across all language versions)
Which index type should be created to support efficient geospatial queries on GeoJSON Point data?
- A 2dsphere index Correct answer.
- A sparse index
- A text index
- A hashed index
Explanation
A 2dsphere index supports queries on GeoJSON geometries using spherical calculations, enabling operators such as $near and $geoWithin. Text and hashed indexes serve different query needs.
Question 21Core MongoDB functionality (shared across all language versions)
A collection has a unique index on email. An insertMany call includes two documents with the same email value. What happens by default?
- The entire batch is rolled back and no documents are inserted.
- The operation stops at the duplicate and documents before it remain inserted. Correct answer.
- Both documents are inserted and the duplicate is flagged later.
- The duplicate document is silently dropped and the rest are inserted.
Explanation
insertMany runs as an ordered operation by default, so it stops at the first error such as a duplicate key violation. Documents inserted before the failing one remain in the collection.
Question 22Core MongoDB functionality (shared across all language versions)
Which aggregation operator returns only the documents from the left collection that have a matching document in the joined collection?
- $facet with a single sub-pipeline
- $lookup with preserveNullAndEmptyArrays set to true
- $lookup followed by $match on the joined array and $unwind without preserveNullAndEmptyArrays Correct answer.
- $graphLookup without a maxDepth
Explanation
A $lookup produces an array of matches, and filtering out empty arrays followed by an unwind that does not preserve nulls yields only matched documents. This effectively performs an inner join.
Question 23Core MongoDB functionality (shared across all language versions)
A query filters on { a: 5, b: 10 } and an index exists on { a: 1, b: 1 }. Which statement best describes index usage?
- The index cannot be used because the filter uses equality on both fields.
- The index supports the query as an equality prefix match on both indexed fields. Correct answer.
- Only the field a can benefit from the index in this query.
- The index is used only if the query includes a sort on b.
Explanation
When all fields of a compound index are constrained by equality, the index provides an efficient prefix match on the full key. The planner can use the complete index key for the lookup.
Question 24Core MongoDB functionality (shared across all language versions)
An aggregation uses $group with _id: null. What is the effect?
- It removes documents where _id is null.
- It groups all input documents into a single group and computes accumulators over the whole set. Correct answer.
- It causes an error because _id cannot be null in $group.
- It groups documents by their _id field values.
Explanation
Setting the group key to null places every input document in one group, which is useful for computing totals or averages across the entire collection. Accumulator expressions then operate over all documents.
Question 25Core MongoDB functionality (shared across all language versions)
A write uses write concern { w: "majority", j: true }. What does this combination require?
- The write is acknowledged after the primary writes it to a temporary file.
- The write is acknowledged only after every secondary has applied it.
- The write is acknowledged as soon as the primary applies it in memory.
- The write is acknowledged after it is applied to the journal on a majority of voting members. Correct answer.
Explanation
w: "majority" requires acknowledgment from a majority of voting replica set members, and j: true requires the write to be committed to the on-disk journal. Together they provide durability against failover and restart.
Question 26Core MongoDB functionality (shared across all language versions)
Which MongoDB data model choice embeds related data inside a single document rather than storing it in a separate collection referenced by an identifier?
- Capping
- Sharding
- Embedding Correct answer.
- Normalization
Explanation
Embedding stores related data as nested subdocuments or arrays within the parent document, so a single read returns the whole aggregate. Referencing instead stores an identifier that must be resolved with a second query or a $lookup stage. Embedding suits one-to-few relationships read together, while referencing suits large or independently updated data.
Question 27Core MongoDB functionality (shared across all language versions)
A developer runs db.orders.insertOne({ _id: 1, total: 50 }) and then db.orders.insertOne({ _id: 1, total: 60 }). What is the outcome of the second call?
- It fails with a duplicate key error because _id values must be unique. Correct answer.
- It succeeds and replaces the first document.
- It succeeds but merges the two documents into one.
- It succeeds and creates a second document with the same _id.
Explanation
Every collection has a unique index on _id, so inserting a document whose _id already exists raises a duplicate key error (E11000). insertOne never overwrites or merges existing documents by default. Replacing a document requires an update or replace operation.
Question 28Core MongoDB functionality (shared across all language versions)
Which command lists the collections present in the current database when using mongosh?
- db.getCollectionNames() Correct answer.
- db.version()
- db.currentOp()
- db.stats()
Explanation
db.getCollectionNames() returns an array of the collection names in the current database. It is a convenience wrapper over the listCollections command. db.stats() returns storage statistics, currentOp shows running operations, and version reports the server build.
Question 29Core MongoDB functionality (shared across all language versions)
Which update operator removes a single matching array element from a field, leaving the rest of the array intact?
- $pull Correct answer.
- $rename
- $pop
- $set
Explanation
$pull removes every element from an array that matches a specified value or condition, preserving the other elements. $pop removes an element by position (first or last) rather than by value. $set and $rename operate on field values, not array membership.
Question 30Core MongoDB functionality (shared across all language versions)
Which aggregation stage writes the results of a pipeline into a new collection, or replaces the entire target collection if it already exists?
- $project
- $match
- $out Correct answer.
- $merge
Explanation
$out writes the pipeline output to a named collection, replacing that collection if it already exists. $merge also persists output but can incorporate results into an existing collection incrementally. $project reshapes documents and $match filters them, neither persisting output.
Question 31Core MongoDB functionality (shared across all language versions)
Which query selects documents whose price field is greater than 10 and less than or equal to 20?
- { price: { $gte: 10, $lt: 20 } }
- { price: { $gt: 10, $lt: 20 } }
- { price: { $gte: 10, $lte: 20 } }
- { price: { $gt: 10, $lte: 20 } } Correct answer.
Explanation
Multiple comparison operators can be combined on one field, and each applies independently, so $gt: 10 with $lte: 20 gives the exclusive lower and inclusive upper bound. The inclusive/exclusive pairing must match the stated conditions exactly.
Question 32Core MongoDB functionality (shared across all language versions)
What is the purpose of the MongoDB Compass application in a developer workflow?
- It is a server-side storage engine that replaces WiredTiger.
- It is a driver that connects Node.js applications to MongoDB.
- It is a backup utility that only performs mongodump operations.
- It is a graphical interface for exploring data, running queries, and building aggregation pipelines. Correct answer.
Explanation
Compass is the official GUI for visually inspecting documents, composing queries and aggregations, and reviewing index and schema information. It is a client tool and does not replace the server storage engine or act as a language driver.
Question 33Core MongoDB functionality (shared across all language versions)
Which BSON type should a field use to store a date value that can be compared and sorted chronologically?
- Date Correct answer.
- String
- ObjectId
- Decimal128
Explanation
The BSON Date type stores a 64-bit integer of milliseconds since the Unix epoch, so dates compare and sort correctly and support date operators such as $year. Storing dates as strings sorts lexicographically and breaks date arithmetic. ObjectId and Decimal128 serve identity and precise numeric roles.
Question 34Core MongoDB functionality (shared across all language versions)
A collection has documents with a nested object address: { city: "Oslo", zip: "0150" }. Which query matches documents whose address.city equals "Oslo"?
- { address: { city: "Oslo" } }
- { address.city: "Oslo" }
- { "address.city": "Oslo" } Correct answer.
- { $where: { address: { city: "Oslo" } } }
Explanation
Dot notation inside a quoted field name, as in "address.city", navigates into embedded documents for both queries and projections. Writing the nested object literally requires an exact match of the entire subdocument, including field order and all fields.
Question 35Core MongoDB functionality (shared across all language versions)
A developer needs to update every document in a collection that has status "stale" and set archived to true. Which call performs this in one operation?
- updateMany({ status: "stale" }, { $set: { archived: true } }) Correct answer.
- updateOne({ status: "stale" }, { $set: { archived: true } })
- replaceOne({ status: "stale" }, { archived: true })
- findOneAndUpdate({ status: "stale" }, { $set: { archived: true } })
Explanation
updateMany applies the update to every document matching the filter, so all stale documents get archived set. updateOne and findOneAndUpdate affect a single matching document. replaceOne swaps the whole document for the replacement, discarding other fields.
Question 36Core MongoDB functionality (shared across all language versions)
Which cursor method should be used to iterate over a very large result set without loading all documents into application memory at once?
- countDocuments()
- explain()
- forEach() with a batch size on the cursor Correct answer.
- toArray()
Explanation
Cursors fetch results in batches, and iterating with a method such as forEach or a for-await loop processes documents incrementally so memory stays bounded. toArray() materializes the entire result set in memory. countDocuments and explain do not stream documents.
Question 37Core MongoDB functionality (shared across all language versions)
An aggregation pipeline needs to compute, for each customer, the total of the amount field across that customer's orders. Which stage accomplishes this?
- { $match: { customerId: 1 } }
- { $sort: { amount: -1 } }
- { $group: { _id: "$customerId", total: { $sum: "$amount" } } } Correct answer.
- { $project: { _id: "$customerId", total: "$amount" } }
Explanation
$group with _id set to the customer field partitions documents by customer, and the $sum accumulator adds each document's amount into a per-group total. $project can compute per-document values but does not aggregate across documents.
Question 38Core MongoDB functionality (shared across all language versions)
A developer wants to add a computed field named discounted to each output document equal to price multiplied by 0.9, keeping other fields. Which stage does this?
- { $addFields: { discounted: { $multiply: ["$price", 0.9] } } } Correct answer.
- { $unset: ["discounted"] }
- { $limit: 10 }
- { $replaceWith: { discounted: { $multiply: ["$price", 0.9] } } }
Explanation
$addFields adds new fields (or overwrites existing ones) while passing all other fields through unchanged. $replaceWith replaces the entire document with the specified expression, dropping fields not included. $unset removes fields and $limit restricts document count.
Question 39Core MongoDB functionality (shared across all language versions)
A query sorts results by a field that is part of a compound index, but the sort direction is the reverse of the index direction. What can be said about index support for the sort?
- The query fails because sort direction must match the index exactly.
- The sort can still use the index because MongoDB can traverse an index in reverse. Correct answer.
- The sort must always perform an in-memory blocking sort.
- The index is automatically rebuilt with the new direction.
Explanation
MongoDB can scan an index in either direction, so a sort on a single indexed field works whether ascending or descending. For compound indexes the sort pattern must still be the reverse of the full index key pattern to be covered. Indexes are not rebuilt automatically for sort direction.
Question 40Core MongoDB functionality (shared across all language versions)
Which statement correctly describes a multikey index?
- It enforces uniqueness across several fields.
- It indexes only the first element of an array.
- It allows multiple collections to share one index definition.
- It indexes each element of an array field so queries on array values can use the index. Correct answer.
Explanation
When an indexed field holds an array, MongoDB creates a multikey index with an entry for each array element, enabling indexed lookups on array membership. A compound index over several fields is a different concept, and uniqueness is controlled by the unique option.
Question 41Core MongoDB functionality (shared across all language versions)
Which expression correctly matches documents whose embedded field items is an array containing the value "pen"?
- { "items.0": "pen" }
- { items: { $all: ["pen"] } }
- { items: { $in: ["pen"] } }
- { items: "pen" } Correct answer.
Explanation
Equality against an array field matches when any element equals the value, so { items: "pen" } finds documents whose array contains "pen". $in and $all also work but are unnecessary for a single value, and a positional path checks only one slot.
Question 42Core MongoDB functionality (shared across all language versions)
A developer creates an index with the option { unique: true } on a field that already contains duplicate values in existing documents. What happens?
- The duplicates are moved to a system collection.
- The index creation fails because the existing data violates the uniqueness constraint. Correct answer.
- The index is created and duplicates are removed automatically.
- The index is created but uniqueness is enforced only for future inserts.
Explanation
Building a unique index validates existing data, and if duplicates exist the build fails with a duplicate key error. MongoDB does not delete or relocate existing documents to satisfy a new index. The data must be cleaned before the index can be created.
Question 43Core MongoDB functionality (shared across all language versions)
Which read preference sends queries to the primary by default and is the standard choice when strong consistency is required?
- primaryPreferred
- secondary
- primary Correct answer.
- nearest
Explanation
The primary read preference routes all reads to the replica set primary, guaranteeing the most current data. secondary and nearest may return stale data from secondaries, and primaryPreferred falls back to a secondary only when no primary is available.
Question 44Core MongoDB functionality (shared across all language versions)
A developer wants to count how many documents in a collection match a filter without retrieving the documents themselves. Which method is appropriate?
- estimatedDocumentCount()
- distinct("field", filter)
- countDocuments(filter) Correct answer.
- find(filter).toArray().length
Explanation
countDocuments runs a server-side count for the given filter and returns the number without transferring documents. estimatedDocumentCount ignores filters and uses collection metadata. distinct returns unique field values, and toArray().length transfers every matching document.
Question 45Core MongoDB functionality (shared across all language versions)
A collection stores documents with a field named _id of type ObjectId. Which statement about querying by _id is correct?
- The query must pass the ObjectId instance, not its hex string, to match the document. Correct answer.
- Any string that looks like an ObjectId matches automatically.
- _id must be supplied as a number.
- _id queries cannot use an index.
Explanation
BSON comparison is type-sensitive, so an ObjectId value only equals another ObjectId with the same bytes; a plain hex string is a different BSON type and will not match. The _id index makes these lookups fast. Applications typically construct ObjectId from the string before querying.
Question 46Core MongoDB functionality (shared across all language versions)
An aggregation pipeline uses $lookup to join orders with a customers collection. Which statement describes the shape of the joined data by default?
- The foreign documents replace the local document entirely.
- Each output document gains an array field containing all matching documents from the foreign collection. Correct answer.
- The join fails unless the foreign field has a unique index.
- The join produces a single merged document with fields from both collections flattened.
Explanation
$lookup adds a new array field to each input document holding the documents from the foreign collection that match the local and foreign field conditions. An empty array appears when nothing matches. A unique index on the foreign field is not required, though it can improve performance.
Question 47Core MongoDB functionality (shared across all language versions)
A query filters on two fields, and a compound index exists on those fields but in the opposite order from the filter. Which statement best describes the likely outcome?
- The query returns incorrect results because the index order differs.
- The index is unusable and a collection scan is guaranteed.
- The index can still be used because MongoDB can match predicates to index fields in any order for an equality filter. Correct answer.
- MongoDB automatically creates a second index to match the query.
Explanation
For equality predicates, MongoDB can use a compound index even when the query lists the fields in a different order than the index key pattern, since equality conditions are order-independent. Index order matters mainly for sorts and range predicates. Results are never affected by index choice.
Question 48Core MongoDB functionality (shared across all language versions)
A developer needs to atomically read a document and set one of its fields in a single operation, returning the document as it was before the change. Which call accomplishes this?
- findOneAndUpdate with returnDocument: "before" Correct answer.
- updateMany with a filter on _id
- replaceOne with upsert: true
- find then updateOne in sequence
Explanation
findOneAndUpdate performs the update atomically on the server and can return either the pre-update or post-update version via returnDocument. Splitting find and update into two calls introduces a race where another write can intervene. replaceOne and updateMany do not return the prior document.
Question 49Core MongoDB functionality (shared across all language versions)
A collection has an index on { a: 1 } and documents include a field b. A query uses the filter { a: 5 } and projects only { b: 1, _id: 0 }. Which statement about execution is accurate?
- The query fails because projections must include indexed fields.
- The query is fully covered by the index and never reads documents.
- The query can use the index to find matching documents but must fetch each document to return b. Correct answer.
- The query cannot use the index because b is not indexed.
Explanation
A covered query requires every field in the filter and projection to be present in the index. Because b is not in the index on a, the server uses the index to locate matches but then fetches documents to obtain b. Adding b to the index would allow a covered plan.
Question 50Core MongoDB functionality (shared across all language versions)
A developer runs an aggregation that begins with $match on an indexed field followed by $group. Why does placing $match first typically improve performance?
- It makes $group unnecessary because filtering already aggregates the data.
- It disables the query planner for the rest of the pipeline.
- It reduces the number of documents entering $group and can use the index before documents are transformed. Correct answer.
- It forces the pipeline to run on the primary only.
Explanation
Early $match filters documents before expensive stages and lets the planner use an index for the initial predicate. Fewer documents then flow into $group, reducing memory and CPU. $match does not disable the planner or perform aggregation itself.