Question 15 / 50
ImportantMediumDebuggingArrays
This update is supposed to mark one skill as verified. What is wrong with it?
db.users.updateOne(
{ _id: ObjectId("64a1b2c3d4e5f6a7b8c90001"), "skills.name": "Node.js" },
{ $set: { "skills.verified": true } }
)Think about it first.
Short answer
skills.verified is not a path to the matched element. It looks like a field on the array itself. Use the positional operator $ or $[elem] with arrayFilters so the matched skill object gets verified: true.
Why?
The filter found the document using a dotted array path, but the update path does not refer to that element. $set: { 'skills.$.verified': true } updates the first matching element. For several matches, arrayFilters is the explicit version.
Example
db.users.updateOne(
{ _id: ObjectId("64a1b2c3d4e5f6a7b8c90001"), "skills.name": "Node.js" },
{ $set: { "skills.$.verified": true } }
)Interview tip
Distinguish 'query matched the document' from 'update targeted the element'. They are different paths.
Common mistake
Using $set on 'skills.verified' and then wondering why the array of objects never changes.
How did you do?
Cheat Sheet