Mongodb Certified Developer Associate C100dev · Free Practice Question Hard
Question 6
You are responsible for a MongoDB database managing customer orders. Each document in the orders collection contains fields like _id, orderId, status, and shippedDate. You want to change the status of an order to "shipped" and set the shippedDate to the current date. The operation should return the document after the update. While you perform this operation, another process updates the same document's status to "processing". You run the following findAndModify operation:
- db.orders.findAndModify({
- query: { orderId: 12345, status: "confirmed" },
- update: { $set: { status: "shipped", shippedDate: new Date() } },
- new: true
- })
Almost simultaneously, another operation executes:
- db.orders.updateOne(
- { orderId: 12345 },
- { $set: { status: "processing" } }
- )
What will be the outcome of the findAndModify operation, and what will be the state of the orders collection after both operations?
-
A
Output of
findAndModify: The document with status"confirmed"and noshippedDate.Final State: The order has status
"processing"with noshippedDatefield. -
B
Output of
findAndModify: The document with status"shipped"and the currentshippedDate.Final State: The order has status
"processing"with noshippedDatefield. -
C
Output of
findAndModify: The document with status"shipped"and the currentshippedDate.Final State: The order has status
"shipped"with theshippedDateset. -
D
Output of
findAndModify: The document with status"processing"and noshippedDate.Final State: The order has status
"shipped"with theshippedDateset.
Reveal correct answer
Correct answer: B
A.
The findAndModify operation successfully updates the document, so it would not return the status "confirmed" (the initial state). The document status cannot remain "confirmed" after either operation.
B.
The findAndModify operation returns the document with the status "shipped" and the current shippedDate because it executes first, locking the document. After the update, the other operation changes the status to "processing", which means the final state of the document reflects "processing" as the status, but the shippedDate remains set by the first operation.
C.
The final state of the document would not remain "shipped" because the concurrent update changes it to "processing". The findAndModify command does correctly set the shippedDate, but the status is changed afterward.
D.
The findAndModify operation completes before the concurrent updateOne, so it does not return the "processing" status. The final state would not be "shipped" if the second operation ran afterward.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
