How to Use $push Operator 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 statement 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 its 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 updates happen. - Not using
$eachwhen pushing multiple values, which results in pushing the entire array as a single element.
Correct usage for pushing multiple values:
mongodb
db.users.updateOne(
{ name: "Alice" },
{ $push: { hobbies: { $each: ["cycling", "hiking"] } } }
)Output
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
Quick Reference
| Operator | Description | Example |
|---|---|---|
| $push | Add a single element to an array | { $push: { hobbies: "reading" } } |
| $push with $each | Add multiple elements to an array | { $push: { hobbies: { $each: ["swimming", "running"] } } } |
| $push with $position | Insert element at specific position | { $push: { hobbies: { $each: ["chess"], $position: 0 } } } |
| $push with $slice | Limit array size after push | { $push: { hobbies: { $each: ["gaming"], $slice: -3 } } } |
| $push with $sort | Sort array after push | { $push: { scores: { $each: [90], $sort: -1 } } } |
Key Takeaways
Use
$push to add elements to an array field in MongoDB documents.If the array field does not exist,
$push creates it with the new element.Use
$each inside $push to add multiple elements at once.Avoid pushing to fields that are not arrays to prevent errors.
Combine
$push with $position, $slice, and $sort for advanced array updates.