$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.

CategoryUpdate Modifier
MongoDB Version2.6+
Example Languagemongosh (Shell)

📝 Syntax

{ $push: { <array field>: { $each: [ <value> ], $position: <position> } } }

⚙️ Parameters

array fieldThe array field to insert into.
positionThe 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

📚 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏