MongoDB Query to Push to Array with Examples
$push operator in an updateOne or updateMany query like db.collection.updateOne({filter}, {$push: {arrayField: newValue}}) to add an element to an array.Examples
How to Think About It
$push operator in an update query. You specify which document to update using a filter, then tell MongoDB to add the new value to the array field. This lets you grow arrays without replacing the whole array.Algorithm
Code
db.users.updateOne(
{ _id: 1 },
{ $push: { hobbies: 'reading' } }
);
print('Updated document:', db.users.findOne({_id: 1}));Dry Run
Let's trace pushing 'reading' into the hobbies array of user with _id 1.
Find document
Locate document where _id = 1: { _id: 1, name: 'Alice', hobbies: [] }
Apply $push
Add 'reading' to hobbies array: hobbies becomes ['reading']
Return updated document
{ _id: 1, name: 'Alice', hobbies: ['reading'] }
| Step | Action | Array State |
|---|---|---|
| 1 | Find document with _id=1 | [] |
| 2 | Push 'reading' to hobbies | ['reading'] |
| 3 | Return updated document | ['reading'] |
Why This Works
Step 1: Use $push operator
The $push operator tells MongoDB to add a new element to the end of an array field without replacing the whole array.
Step 2: Specify filter to find document
You provide a filter like {_id: 1} to select which document to update.
Step 3: Update the document
MongoDB updates the matched document by appending the new value to the specified array field.
Alternative Approaches
db.users.updateOne({ _id: 1 }, { $addToSet: { hobbies: 'reading' } });db.users.updateOne({ _id: 1 }, { $push: { hobbies: { $each: ['reading', 'swimming'] } } });Complexity: O(1) time, O(1) space
Time Complexity
The update operation with $push runs in constant time because it targets a single document and appends to an array.
Space Complexity
Only the new element is added to the array, so space grows linearly with the number of pushed elements.
Which Approach is Fastest?
$push is simple and fast for adding elements. $addToSet adds a check for duplicates, which can be slightly slower.
| Approach | Time | Space | Best For |
|---|---|---|---|
| $push | O(1) | O(1) | Simple append to array |
| $addToSet | O(1) with duplicate check | O(1) | Appending unique elements only |
| $push with $each | O(n) for n elements | O(n) | Adding multiple elements at once |
$addToSet instead of $push to avoid duplicate entries in the array.$push inside the update operator and trying to set the array directly replaces it instead of adding.