How to Use $push in MongoDB: Syntax and Examples
In MongoDB, the
$push operator adds a value to an array field in a document. You use it inside an update command to append new elements to an existing array or create the array if it doesn't exist.Syntax
The $push operator is used in an update operation to add an element to an array field. It has this basic form:
{ $push: { <field>: <value> } }- Adds<value>to the array at<field>.- If the array field does not exist, MongoDB creates it with the pushed value as the first element.
mongodb
db.collection.updateOne(
{ <filter> },
{ $push: { <field>: <value> } }
)Example
This example shows how to add a new hobby to a user's hobbies array. If the hobbies array does not exist, it will be created.
mongodb
db.users.updateOne(
{ name: "Alice" },
{ $push: { hobbies: "painting" } }
)
// After update, the document might look like:
// { name: "Alice", hobbies: ["painting"] }Output
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
Common Pitfalls
Common mistakes when using $push include:
- Trying to push to a field that is not an array, which causes an error.
- Using
$pushwithout a filter that matches documents, so no documents get updated. - Forgetting that
$pushadds duplicates; it does not check for existing values.
To avoid duplicates, use $addToSet instead.
mongodb
/* Wrong: pushing to a non-array field */ db.users.updateOne( { name: "Bob" }, { $push: { age: 30 } } // 'age' is a number, not an array ) /* Right: push to an array field */ db.users.updateOne( { name: "Bob" }, { $push: { hobbies: "cycling" } } )
Quick Reference
| Operator | Description | Notes |
|---|---|---|
| $push | Adds a value to an array field | Creates array if field missing |
| $addToSet | Adds value only if not present | Prevents duplicates |
| $each | Used with $push to add multiple values | Example: { $push: { arr: { $each: [1,2,3] } } } |
Key Takeaways
Use $push to add elements to an array field in MongoDB documents.
$push creates the array if it does not exist in the document.
$push can add duplicate values; use $addToSet to avoid duplicates.
Always ensure the target field is an array or does not exist before using $push.
Combine $push with $each to add multiple elements at once.