Challenge - 5 Problems
MongoDB Array Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
What is the result of this $push update?
Given a document
{ _id: 1, fruits: ["apple", "banana"] }, what will be the fruits array after running this update?db.collection.updateOne({ _id: 1 }, { $push: { fruits: "orange" } })Attempts:
2 left
💡 Hint
The $push operator adds the new element to the end of the existing array.
✗ Incorrect
The $push operator appends the specified value to the array field. Here, "orange" is added to the end of the existing fruits array.
📝 Syntax
intermediate2:00remaining
Which update query correctly uses $push to add multiple elements?
You want to add the elements "grape" and "melon" to the
fruits array in one update. Which query is correct?Attempts:
2 left
💡 Hint
Use $each inside $push to add multiple elements.
✗ Incorrect
To add multiple elements with $push, you must use the $each modifier. Options B and C use invalid operators, and A pushes the entire array as one element.
❓ optimization
advanced2:00remaining
How to efficiently add unique elements to an array?
You want to add "kiwi" to the
fruits array only if it does not already exist. Which update query achieves this efficiently?Attempts:
2 left
💡 Hint
Use an operator designed to add unique elements to arrays.
✗ Incorrect
$addToSet adds the element only if it is not already present. $push always adds the element, possibly creating duplicates.
🧠 Conceptual
advanced2:00remaining
What happens if you $push to a non-array field?
Consider a document
{ _id: 1, fruits: "apple" }. What happens if you run:db.collection.updateOne({ _id: 1 }, { $push: { fruits: "banana" } })Attempts:
2 left
💡 Hint
Think about the data type requirements for $push.
✗ Incorrect
$push requires the target field to be an array. If it is not, the update fails with an error.
🔧 Debug
expert2:00remaining
Why does this $push update not add the element?
You run this update:
The
db.collection.updateOne({ _id: 1 }, { $push: { fruits: { $each: ["pear"], $slice: 2 } } })The
fruits array was ["apple", "banana"] before. After the update, it remains unchanged. Why?Attempts:
2 left
💡 Hint
Understand how $slice works with $push and $each.
✗ Incorrect
$slice limits the array size after adding new elements. A positive $slice keeps only the first N elements. Since the array was already size 2, adding one element and slicing to 2 keeps only the first two elements, effectively discarding the new one.