On this page本页内容
$position
¶The $position
modifier specifies the location in the array at which the $push
operator inserts elements. $position
修饰符指定数组中$push
运算符插入元素的位置。Without the 如果不使用$position
modifier, the $push
operator inserts elements to the end of the array. $position
修饰符,$push
运算符会将元素插入数组的末尾。See $push modifiers for more information.有关更多信息,请参阅$push
修饰符。
To use the 要使用$position
modifier, it must appear with the $each
modifier.$position
修饰符,它必须与$each
修饰符一起出现。
Changed in version 3.6.在版本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.$position
可以接受一个负的数组索引值,以指示从数组的最后一个元素开始计数(但不包括)的位置。
<num>
indicates the position in the array, based on a zero-based index:根据从零开始的索引指示数组中的位置:
<num>
is greater or equal to the length of the array, the $position
modifier has no effect and $push
adds elements to the end of the array.<num>
的值大于或等于数组的长度,$position
修饰符无效,$push
会将元素添加到数组的末尾。-1
indicates the position just before the last element in the array. -1
表示数组中最后一个元素之前的位置。$each
array, the last added element is in the specified position from the end. $each
数组中指定多个元素,则最后添加的元素位于从末尾开始的指定位置。<num>
is greater than or equal to the length of the array, the $push
adds elements to the beginning of the array.<num>
的绝对值大于或等于数组的长度,$push
会将元素添加到数组的开头。Consider a collection 考虑一个包含下列文档的集合students
that contains the following document:students
:
The following operation updates the 以下操作更新scores
field to add the elements 50
, 60
and 70
to the beginning of the array:scores
字段,将元素50
、60
和70
添加到数组的开头:
The operation results in the following updated document:该操作将生成以下更新的文档:
Consider a collection 考虑一个包含下列文件的集合students
that contains the following document:students
:
The following operation updates the 以下操作将更新scores
field to add the elements 20
and 30
at the array index of 2
:scores
字段,以在数组索引2
处添加元素20
和30
:
The operation results in the following updated document:该操作将生成以下更新的文档:
Changed in version 3.6:在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. $position
可以接受一个负的数组索引值,以指示从数组的最后一个元素开始计数(但不包括)的位置。For example, 例如,-1
indicates the position just before the last element in the array.-1
表示数组中最后一个元素之前的位置。
Consider a collection 考虑一个集合students
that contains the following document:students
包含下列文档:
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.$position
指定-2
,在最后一个元素之前的两个位置处添加90
,然后在最后一个元素之前的两个位置处添加80
。
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.$each
数组中指定多个元素,则最后添加的元素位于从末尾开始的指定位置。
The operation results in the following updated document:该操作将生成以下更新的文档: