$push (Append to Array)
Last updated: 2026-10-09
$push (Append to Array)
$push appends one or more elements to the end of an array. `{ $push: { items: 'pen' } }`; for several values at once combine with $each. It also composes with $position (insertion point), $slice (length cap) and $sort (ordering) for advanced array maintenance. It is the most-used array update operator.
| Category | Update Array |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $push: { <array field>: <value> } }
⚙️ Parameters
| array field | The array field to append to. |
|---|---|
| value | The value to append, or the { $each: [...] } form. |
Returns:The update result
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $push: append an element
// Duplicates are allowed
db.carts.updateOne(
{ _id: 1 },
{ $push: { items: 'pen' } }
)
// Append several at once
// Requires $each
db.carts.updateOne(
{ _id: 1 },
{ $push: { items: { $each: ['book', 'ruler'] } } }
)
Output:
// items gains pen, then book and ruler; duplicates allowed
📌 Notes
- Appends at the end by default; use $addToSet for dedup
- Batch appends require $each
- Combine $position/$slice/$sort to control position and length
🏷️ Related Tags
💡 Related Cases
Array and Nested Document Queries
Hands-On: CRUD for a Blog Comment System
Document Update: A Detailed Explanation of `updateOne` and `updateMany`
📚 Related Tutorials
❓ FAQ
QWhat is the difference between $push and $addToSet?
A$push appends and allows duplicates; $addToSet dedups first.
QCan $push insert at a specific position?
AYes, with $position to set the index.
QCan $push cap the array length?
AYes, with $slice — e.g. keep only the latest 10.