Mongodb Certified Developer Associate C100dev · Free Practice Question Easy
Question 4
Consider a collection named employees with the following document:
- {
- "_id" : ObjectId("5f0a7e80d8c9c7b5a48c49e1"),
- "name" : "John Doe",
- "position" : "Developer",
- "department" : "IT",
- "hire_date" : ISODate("2021-01-01T00:00:00.000Z")
- }
What is the query to update the "position" field for the employee with "_id" equal to ObjectId("5f0a7e80d8c9c7b5a48c49e1") to "Manager"?
-
A
- db.employees.updateOne(
- { _id: ObjectId("5f0a7e80d8c9c7b5a48c49e1") },
- { $update: { position: "Manager" } }
- )
-
B
- db.employees.updateOne(
- { _id: ObjectId("5f0a7e80d8c9c7b5a48c49e1") },
- { $set: { position: "Manager" } }
- )
-
C
- db.employees.updateOne(
- { _id: ObjectId("5f0a7e80d8c9c7b5a48c49e1") },
- { $unset: { position: "Manager" } }
- )
-
D
- db.employees.updateOne(
- { $set: { position: "Manager" } }
- )
Reveal correct answer
Correct answer: B
A.
It uses an incorrect update operator $update which does not exist in MongoDB. The correct update operator to set the value of a field is $set.
B.
Here's an explanation of this query:
db.employees.updateOne: This method is used to update a single document in the "employees" collection.{ _id: ObjectId("5f0a7e80d8c9c7b5a48c49e1") }: This is the filter condition specifying which document to update. It matches the document with the "_id" equal to ObjectId("5f0a7e80d8c9c7b5a48c49e1").{ $set: { position: "Manager" } }: This is the update operation. It uses the$setoperator to set the value of the "position" field to "Manager" for the matched document.
C.
It uses the $unset operator, which is used to remove a field from a document, rather than $set operator to update the value of the "position" field. Additionally, the usage of { position: "Manager" } within $unset is incorrect because $unset does not take a value for the field to be removed.
D.
It is missing the filter condition to specify which document to update. Without specifying the filter condition the update operation will be applied to all documents in the collection, setting their "position" field to "Manager".
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
