Mongodb Certified Developer Associate C100dev · Free Practice Question Easy

Question 21

In a MongoDB collection named products, each document contains information about a product, including product_id, name, price, and stock_quantity. The price of a product with product_id 501 needs to be updated to $19.99 due to a pricing change. Which MongoDB update query should you use to correctly update the price of the product where product_id is 501?

  • A

    db.products.update({ "product_id": 501 }, { $set: { "price": 19.99 } })

  • B

    db.products.updateOne({ "product_id": 501 }, { $set: { "price": 19.99 } })

  • C

    db.products.update({ "product_id": 501 }, { "price": 19.99 })

  • D

    db.products.updateOne({ "product_id": { $eq: 501 } }, { $set: { "price": 19.99 } })

Reveal correct answer

Correct answer: B

A.

This query will correctly update the price, but the update method can match and update multiple documents if they meet the criteria, which might be unintended if product_id should be unique. Moreover, update is an older method, and its use is generally discouraged in favor of updateOne or updateMany.

B.

This query is the most appropriate for updating a single document based on a simple equality constraint. The updateOne method ensures that only one document is updated, which is the expected behavior when working with a unique product_id. The $set operator correctly modifies only the price field without affecting other fields.

C.

This query attempts to update the document but incorrectly uses the update document format. Without the $set operator, this will replace the entire document with just the price field, deleting all other fields from the document, which is almost certainly not the intended action.

D.

Although this query will work, using $eq in the filter condition is unnecessary for simple equality checks. The presence of $eq does not add any benefit in this context and might make the query harder to read.

Discussion

Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.

You must be logged in to post a comment.

Preparing For

Your Certification?

255+ certifications
Detailed explanations
Free PDF samples

Has All The Questions You Need