0
0
MongodbHow-ToBeginner · 2 min read

MongoDB Query to Push to Array with Examples

Use the $push operator in an updateOne or updateMany query like db.collection.updateOne({filter}, {$push: {arrayField: newValue}}) to add an element to an array.
📋

Examples

Inputdb.users.updateOne({_id: 1}, {$push: {hobbies: 'reading'}})
OutputThe 'reading' string is added to the hobbies array of the user with _id 1.
Inputdb.products.updateOne({name: 'Pen'}, {$push: {tags: 'stationery'}})
OutputThe 'stationery' tag is appended to the tags array of the product named 'Pen'.
Inputdb.orders.updateOne({_id: 5}, {$push: {items: {product: 'book', qty: 1}}})
OutputA new object {product: 'book', qty: 1} is added to the items array of the order with _id 5.
🧠

How to Think About It

To add a new element to an array inside a MongoDB document, you use the $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

1
Identify the document(s) to update using a filter.
2
Use the <code>$push</code> operator to specify the array field and the new element to add.
3
Run the update query to add the element to the array.
4
Verify the array now contains the new element.
💻

Code

mongodb
db.users.updateOne(
  { _id: 1 },
  { $push: { hobbies: 'reading' } }
);

print('Updated document:', db.users.findOne({_id: 1}));
Output
{ _id: 1, name: 'Alice', hobbies: ['reading'] }
🔍

Dry Run

Let's trace pushing 'reading' into the hobbies array of user with _id 1.

1

Find document

Locate document where _id = 1: { _id: 1, name: 'Alice', hobbies: [] }

2

Apply $push

Add 'reading' to hobbies array: hobbies becomes ['reading']

3

Return updated document

{ _id: 1, name: 'Alice', hobbies: ['reading'] }

StepActionArray State
1Find document with _id=1[]
2Push 'reading' to hobbies['reading']
3Return 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

Use $addToSet operator
mongodb
db.users.updateOne({ _id: 1 }, { $addToSet: { hobbies: 'reading' } });
Adds the element only if it does not already exist in the array, preventing duplicates.
Use $push with $each for multiple values
mongodb
db.users.updateOne({ _id: 1 }, { $push: { hobbies: { $each: ['reading', 'swimming'] } } });
Allows pushing multiple elements at once into the array.

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.

ApproachTimeSpaceBest For
$pushO(1)O(1)Simple append to array
$addToSetO(1) with duplicate checkO(1)Appending unique elements only
$push with $eachO(n) for n elementsO(n)Adding multiple elements at once
💡
Use $addToSet instead of $push to avoid duplicate entries in the array.
⚠️
Forgetting to use $push inside the update operator and trying to set the array directly replaces it instead of adding.