$position (Set Insert Position)
Last updated: 2026-10-09
$position (Set Insert Position)
$position sets where $push inserts elements. `{ $push: { items: { $each: ['x'], $position: 0 } } }` inserts at the start. Positions start at 0; negative values count from the end (-1 inserts before the last element). It must be used inside $push with $each and composes with $slice to cap the array length.
| Category | Update Modifier |
|---|---|
| MongoDB Version | 2.6+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $push: { <array field>: { $each: [ <value> ], $position: <position> } } }
⚙️ Parameters
| array field | The array field to insert into. |
|---|---|
| position | The insertion index, starting at 0; negatives count from the end. |
Returns:The update result
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $position: insert at the array start
// Positions start at 0
db.tasks.updateOne(
{ _id: 1 },
{ $push: { queue: { $each: ['urgent'], $position: 0 } } }
)
// Negative: insert before the last element
db.tasks.updateOne(
{ _id: 1 },
{ $push: { queue: { $each: ['normal'], $position: -1 } } }
)
Output:
// urgent lands at the front; normal lands before the last element
📌 Notes
- Requires $each alongside it
- Positions start at 0; negatives count from the end
- Combine with $slice to cap the array length
🏷️ Related Tags
💡 Related Cases
📚 Related Tutorials
❓ FAQ
QMust $position be paired with $each?
AYes, $position works only inside $push together with $each.
QWhat does $position: 0 mean?
AInsert at the array start (index 0).
QDoes $position support negatives?
AYes, -1 inserts before the last element.