- Reference >
- Operators >
- Update Operators >
- Array Update Operators >
- $position
$position¶
On this page
Definition¶
-
$position¶ New in version 2.6.
The
$positionmodifier specifies the location in the array at which the$pushoperator insert elements. Without the$positionmodifier, the$pushoperator inserts elements to the end of the array. See $push modifiers for more information.To use the
$positionmodifier, it must appear with the$eachmodifier.The
<num>is a non-negative number that corresponds to the position in the array, based on a zero-based index.If the
<num>is greater or equal to the length of the array, the$positionmodifier has no effect and$pushadds elements to the end of the array.
Examples¶
Add Elements at the Start of the Array¶
Consider a collection students that contains the following document:
The following operation updates the scores field to add the
elements 50, 60 and 70 to the beginning of the array:
The operation results in the following updated document:
Add Elements to the Middle of the Array¶
Consider a collection students that contains the following document:
The following operation updates the scores field to add the
elements 20 and 30 at the array index of 2:
The operation results in the following updated document: