0
0
MongoDBquery~20 mins

$slice modifier with $push in MongoDB - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
MongoDB $slice Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
query_result
intermediate
2:00remaining
What is the output after using $push with $slice?

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?

A[30, 40, 50]
B[10, 20, 30, 40, 50]
C[20, 30, 40, 50]
D[40, 50]
Attempts:
2 left
💡 Hint

Remember that $slice with a negative number keeps the last N elements.

📝 Syntax
intermediate
2:00remaining
Which update query is syntactically correct for $push with $slice?

Choose the syntactically valid MongoDB update query that uses $push with $slice to limit array size.

A{ $push: { items: { $each: [1,2,3], $slice: -2 } } }
B{ $push: { items: { $slice: -2, $each: [1,2,3] } } }
C{ $push: { items: { $each: [1,2,3], $slice: 2 } } }
D{ $push: { items: { $each: [1,2,3], $limit: 2 } } }
Attempts:
2 left
💡 Hint

The order of $each and $slice matters, and $limit is not a valid modifier.

optimization
advanced
2:00remaining
How to efficiently keep only the last 5 elements in an array using $push?

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?

A{ $push: { logs: { $each: newEntries, $sort: -1, $slice: 5 } } }
B{ $push: { logs: { $each: newEntries } }, $slice: -5 }
C{ $push: { logs: newEntries }, $slice: -5 }
D{ $push: { logs: { $each: newEntries, $slice: -5 } } }
Attempts:
2 left
💡 Hint

Remember that $slice must be inside the $push modifier with $each.

🔧 Debug
advanced
2:00remaining
Why does this $push update with $slice not work as expected?

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?

ABecause $slice must be negative to work with $each.
BBecause $each must be after $slice in the query.
CBecause $slice with positive number keeps the first N elements, not the last.
DBecause $slice only works with $pop, not $push.
Attempts:
2 left
💡 Hint

Think about what positive and negative values for $slice mean.

🧠 Conceptual
expert
2:00remaining
What happens if $slice is zero in a $push update?

In MongoDB, if you run this update:

{ $push: { arr: { $each: [7,8], $slice: 0 } }}

What will be the resulting arr array?

AThe array will contain only [7,8].
BThe array will be empty after the update.
CThe array will remain unchanged.
DThe update will cause a syntax error.
Attempts:
2 left
💡 Hint

Think about what $slice: 0 means for array length.