Consider a MongoDB document with an array field scores initially as [10, 20, 30]. We run this update:
{ $push: { scores: { $each: [40, 50], $slice: -3 } }}What will be the scores array after this update?
Remember that $slice with a negative number keeps the last N elements.
The $push with $each adds 40 and 50 to the array, making it [10, 20, 30, 40, 50]. Then $slice: -3 keeps only the last 3 elements, which are [30, 40, 50].
Choose the syntactically valid MongoDB update query that uses $push with $slice to limit array size.
The order of $each and $slice matters, and $limit is not a valid modifier.
Option A is correct because $each and $slice are used properly, and $slice can be negative to keep last N elements. Option A uses positive slice which keeps first N elements but is valid syntax too, but the question asks for correct syntax with negative slice. Option A has wrong order, and Option A uses invalid $limit.
You want to add multiple elements to an array field logs and keep only the last 5 elements to save space. Which update query is the most efficient?
Remember that $slice must be inside the $push modifier with $each.
Option D correctly uses $each to add multiple elements and $slice: -5 to keep the last 5 elements. Option D and C place $slice outside $push, which is invalid. Option D uses $sort which is not a valid modifier in this context.
Given this update query:
{ $push: { data: { $each: [5,6], $slice: 2 } }}The array data ends up with only the first 2 elements instead of the last 2. Why?
Think about what positive and negative values for $slice mean.
A positive $slice keeps the first N elements of the array after pushing. To keep the last N elements, $slice must be negative. So the array keeps the first 2 elements, not the last 2.
In MongoDB, if you run this update:
{ $push: { arr: { $each: [7,8], $slice: 0 } }}What will be the resulting arr array?
Think about what $slice: 0 means for array length.
$slice: 0 means keep zero elements, so after pushing the new elements, the array is trimmed to zero length, resulting in an empty array.