MPD

Free MPD practice questions

10 questions from our MPD practice tests, each with the correct answer and a written explanation. Read them with the answers shown, or switch to quiz mode and answer first.

Back to the MPD practice exams

Question 1 of 10, MongoDB Overview and the Document Model

Which components make up a 12-byte ObjectId value generated by a MongoDB driver?

  1. AA 4-byte timestamp, a 5-byte per-process random value, and a 3-byte counter Correct answer
  2. BA 4-byte machine IP address, a 4-byte process id, and a 4-byte sequence assigned by the primary
  3. CAn 8-byte timestamp in milliseconds followed by a 4-byte hash of the collection name
  4. DA 6-byte MAC address of the client host and a 6-byte counter shared by all clients connected to the cluster

Answer and explanation: An ObjectId contains a 4-byte seconds timestamp, a 5-byte per-process random value, and a 3-byte counter, so it is roughly sortable by creation time. It does not include a millisecond timestamp, a collection hash, IP or MAC addresses, and it is generated by the client without coordinating with the primary.

Question 2 of 10, CRUD Operations

A pipeline sorts 5 million documents on an unindexed field and fails because a blocking sort exceeded its memory limit in an older configuration. What is the correct remedy in PyMongo?

  1. AReplace $sort with $sortByCount, which does not use the blocking sort memory
  2. BPass batch_size=5000000 to aggregate so all documents arrive in one batch
  3. CAdd a $limit of 100 at the very end of the pipeline, after the $sort and every other stage
  4. DPass allowDiskUse=True to aggregate, or add an index that supplies the sort order Correct answer

Answer and explanation: allowDiskUse lets blocking stages spill to temporary files (and is the default since 6.0 via allowDiskUseByDefault), while an index can remove the blocking sort entirely. A huge batch size does not change stage memory, a limit placed only after the sort still needs memory unless it coalesces with it into a top-k sort, and $sortByCount groups documents rather than sorting them.

Question 3 of 10, CRUD Operations

A pipeline must output, per customer, the total amount of completed orders sorted from highest to lowest total. Which stage order is MOST efficient and correct?

  1. A$sort on amount descending, then $group by customer with $sum, then $match on status
  2. B$match on status, then $group by customer with $sum, then $sort on the total descending Correct answer
  3. C$group by customer and status with $sum, then $sort on the total, then $project the customers
  4. D$group by customer with $sum, then $match on status, then $sort on the total descending

Answer and explanation: Filtering first with $match reduces the documents entering $group and can use an index on status; sorting after grouping orders customers by total. Matching on status after $group fails because status is no longer a field, sorting raw amounts before grouping does not order totals, and grouping by status too produces per-status totals without excluding non-completed orders.

Question 4 of 10, CRUD Operations

Orders store items: [{product: 'pen', qty: 2}, {product: 'ink', qty: 30}]. The team needs orders that contain at least one single item where product is 'ink' AND qty is greater than 20. Which filter is correct?

  1. A{"items": {"product": "ink", "qty": {"$gt": 20}}}
  2. B{"items": {"$all": [{"product": "ink"}, {"qty": {"$gt": 20}}]}}
  3. C{"items.product": "ink", "items.qty": {"$gt": 20}}
  4. D{"items": {"$elemMatch": {"product": "ink", "qty": {"$gt": 20}}}} Correct answer

Answer and explanation: $elemMatch requires that one array element satisfy all conditions together. Dot-notation conditions can be satisfied by different elements (ink in one, qty>20 in another), the embedded-document form demands an exact element match and treats $gt literally, and $all with these documents matches separate elements exactly rather than combining the criteria.

Question 5 of 10, CRUD Operations

Students have grades: [{course, score}]. An update must change the score of only the 'math' element for student 42. Which update_one call is correct?

  1. Aupdate_one({"_id": 42, "grades.course": "math"}, {"$set": {"grades": {"course": "math", "score": 95}}})
  2. Bupdate_one({"_id": 42, "grades.course": "math"}, {"$set": {"grades.$.score": 95}}) Correct answer
  3. Cupdate_one({"_id": 42}, {"$set": {"grades.$.score": 95}}), relying on the course field
  4. Dupdate_one({"_id": 42}, {"$set": {"grades.math.score": 95}}), using math as a path

Answer and explanation: The positional $ refers to the first array element matched by the array condition in the filter, so the filter must include grades.course. Without an array condition the $ has nothing to resolve and the update fails, setting grades to one subdocument replaces the whole array and loses the other courses, and grades.math treats math as a field name.

Question 6 of 10, CRUD Operations

Each project document has a tasks array of subdocuments with priority and status fields. The team must mark only the low-priority tasks as done, in every project, with one update call. Which PyMongo call does this?

  1. Aupdate_many({}, {"$set": {"tasks.status": "done"}}, array_filters=[{"tasks.priority": "low"}])
  2. Bupdate_many({"tasks.priority": "low"}, {"$set": {"tasks.$.status": "done"}}), which updates matching task elements
  3. Cupdate_one({"tasks.priority": "low"}, {"$set": {"tasks.$[].status": "done"}}, upsert=False)
  4. Dupdate_many({}, {"$set": {"tasks.$[low].status": "done"}}, array_filters=[{"low.priority": "low"}]) Correct answer

Answer and explanation: The filtered positional operator with array_filters updates every array element whose priority is low, in all documents. The positional $ changes only the first matching element per document, a path without an identifier cannot use array_filters or traverse the array, and update_one with $[] touches one project and marks all of its tasks.

Question 7 of 10, Indexes

Analysts query {country: X, city: Y} and also {country: X} sorted by signupDate. Which index set gives good coverage with the fewest indexes?

  1. A{country: 1} alone, since both of the queries filter on the country field
  2. B{country: 1, city: 1, signupDate: 1} alone for both of the query shapes
  3. C{country: 1, city: 1} and {country: 1, signupDate: 1} Correct answer
  4. D{city: 1, country: 1} and {signupDate: 1, country: 1}

Answer and explanation: The first index serves the two equality fields, and the second lets the country equality be followed by an index-supported sort. A three-field index cannot sort by signupDate after equality on country alone because city sits between them, leading with city or signupDate weakens the country filter, and a single country index leaves a blocking sort.

Question 8 of 10, Indexes

A sessions collection must automatically delete each document one hour after its createdAt value. Which index definition achieves this?

  1. Acreate_index("createdAt", expireAfterSeconds=3600) on a field holding Unix epoch integers
  2. Bcreate_index("createdAt", expireAfterSeconds=3600) on a field holding BSON date values Correct answer
  3. Ccreate_index("createdAt", unique=True, expireAfterSeconds=60) with a background cleanup job
  4. Dcreate_index([("userId", 1), ("createdAt", 1)], expireAfterSeconds=3600) as a compound index

Answer and explanation: A TTL index is a single-field index with expireAfterSeconds on a field containing BSON dates (or arrays of dates); the TTL monitor deletes expired documents. Integer timestamps never expire, TTL is ignored on compound indexes, and a 60-second value with uniqueness neither matches the one-hour requirement nor needs an extra job.

Question 9 of 10, Drivers (Python). Choose 2.

A PyMongo insert_many call with ordered=True inserts 1,000 documents, and document 400 violates a unique index. Which statements are true? (Choose two.)

  1. AThe duplicate is skipped and the other 999 documents are inserted without an error
  2. BThe documents before the failing one remain inserted and the remaining documents are not attempted Correct answer
  3. CPyMongo raises DuplicateKeyError and discards the information about inserted documents
  4. DA pymongo.errors.BulkWriteError is raised whose details describe the write error Correct answer
  5. EAll 1,000 inserts are rolled back automatically because insert_many is atomic

Answer and explanation: With ordered=True the server stops at the first error, so earlier inserts persist and later ones are skipped, and PyMongo raises BulkWriteError with details such as writeErrors and nInserted. insert_many is not atomic without a transaction, continuing past the error requires ordered=False and still raises, and DuplicateKeyError is raised for single-document writes such as insert_one.

Question 10 of 10, Drivers (Python)

A developer must update an order and decrement inventory atomically across two collections using PyMongo against an Atlas replica set. Which approach is correct?

  1. AUse bulk_write with ordered=True on each collection, because ordered bulk writes are rolled back on any failure
  2. BSet write concern w='majority' on both collections, which makes the two separate updates commit as one unit
  3. CCall client.start_transaction() and run the two updates normally, because the client tracks the active transaction
  4. DStart a session, call session.with_transaction(callback), and pass session=session to each operation inside the callback Correct answer

Answer and explanation: Multi-document transactions in PyMongo run on a ClientSession, and every operation must receive session=session; with_transaction also retries transient errors. MongoClient has no start_transaction method, ordered bulk writes stop at an error but never roll back earlier writes, and write concern controls durability, not atomicity across operations.