- Reference >
- Operators >
- Update Operators >
- Array Update Operators >
- $position
$position¶
On this page
Definition¶
-
$position¶ The
$positionmodifier specifies the location in the array at which the$pushoperator inserts 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.Changed in version 3.6:
$positioncan accept a negative array index value to indicate the position starting from the end, counting from (but not including) the last element of the array.<num>indicates the position in the array, based on a zero-based index:- A non-negative number corresponds to the position in the array,
starting from the beginning of the array. If the value of
<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. - A negative number corresponds to the position in the array,
counting from (but not including) the last element of the array.
For example,
-1indicates the position just before the last element in the array. If you specify multiple elements in the$eacharray, the last added element is in the specified position from the end. If the absolute value of<num>is greater than or equal to the length of the array, the$pushadds elements to the beginning of the array.
- A non-negative number corresponds to the position in the array,
starting from the beginning of the array. If the value of
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:
Use a Negative Index to Add Elements to the Array¶
Changed in version 3.6: $position can accept a negative array index value to
indicate the position starting from the end, counting from (but not
including) the last element of the array. For example, -1
indicates the position just before the last element in the array.
Consider a collection students that contains the following document:
The following operation specifies -2 for the $position to
add 90 at the position two places before the last element, and then
80 at the position two places before the last element.
Important
With a negative index position, if you specify multiple elements in
the $each array, the last added element is in the
specified position from the end.
The operation results in the following updated document: