A developer is building a MongoDB application that stores social media posts. Each post document includes an array of comments, and each comment is a subdocument with fields such as author, text, and timestamp. The developer later needs to update a specific comment's text. Which update operation should they use to modify only the targeted comment's text without replacing the entire comments array?
The query includes a condition that matches a specific element in the comments array (comments.author: "Alice"), and the update uses the positional $ operator to set the text field of the first matching array element. This is the correct way to update a single subdocument within an array without replacing the entire array. The $ operator refers to the matched array element, ensuring only that comment is modified.
Why this answer
To update a specific subdocument within an array, MongoDB provides the positional $ operator, which acts as a placeholder for the first array element that matches the query condition. The query must include a filter on the array field to identify which element to update. This approach modifies only the targeted subdocument without affecting other elements or replacing the entire array.
Exam trap
The trap here is assuming that the positional $ operator works without a matching array condition in the query filter, which would cause an error or unintended update.