Given the following document in a collection products:
{
_id: 1,
name: "T-Shirt",
sizes: [
{ size: "S", stock: 10 },
{ size: "M", stock: 5 },
{ size: "L", stock: 0 }
]
}What will be the resulting document after running this update?
db.products.updateOne(
{ _id: 1 },
{ $inc: { "sizes.$[elem].stock": 3 } },
{ arrayFilters: [ { "elem.stock": { $lt: 5 } } ] }
)Look at which array elements have stock less than 5 before the update.
The arrayFilters condition { "elem.stock": { $lt: 5 } } matches sizes with stock less than 5. Initially, only sizes "M" (5) and "L" (0) are checked. Since 5 is not less than 5, only "L" matches. So only "L" stock is incremented by 3 from 0 to 3.
Which of the following update commands will cause a syntax error when trying to update array elements with $[identifier]?
db.orders.updateOne(
{ _id: 101 },
{ $set: { "items.$[item].status": "shipped" } },
{ arrayFilters: [ { "item.qty": { $gte: 2 } } ] }
)Check the syntax of the $gte operator in the array filter.
Option A is missing a colon between $gte and 2, causing a syntax error. The correct syntax is { $gte: 2 }.
You want to increment the score by 1 for all players in the players array whose level is greater than 10.
Which update command is the most efficient and correct?
Consider the filter on the document and the use of arrayFilters to target multiple array elements.
Option D correctly updates one document with _id 5 and increments score for all players with level > 10 using arrayFilters. Option D updates many documents unnecessarily. Option D uses positional operator $ without arrayFilters, which updates only the first matching element. Option D lacks arrayFilters, so it cannot filter array elements.
Given this document:
{ _id: 10, tasks: [ { name: "task1", done: false }, { name: "task2", done: false } ] }And this update command:
db.projects.updateOne(
{ _id: 10 },
{ $set: { "tasks.$[t].done": true } },
{ arrayFilters: [ { "t.done": true } ] }
)Why does this update not change any elements?
Check the condition inside arrayFilters and the initial values.
The array filter { "t.done": true } matches only elements where done is true. Since all tasks have done false, no elements match, so no update occurs.
Consider a document:
{
_id: 20,
orders: [
{ id: 1, items: [ { product: "A", qty: 2 }, { product: "B", qty: 1 } ] },
{ id: 2, items: [ { product: "A", qty: 1 }, { product: "C", qty: 5 } ] }
]
}You want to increment the quantity by 1 for product "A" only in order with id 2.
Which update command achieves this?
Use two different identifiers in arrayFilters to target nested arrays.
Option A correctly uses two identifiers: order to filter orders with id 2, and item to filter items with product "A". The update increments qty by 1 only for matching nested elements.
Other options have swapped identifiers or wrong filter fields.