On this page
$position
在本页面
Definition
$position
- $position修饰符指定$push运算符在数组中插入元素的位置。如果没有$position修饰符,则$push运算符会将元素插入到数组的末尾。有关更多信息,请参见$push modifiers。
要使用$position修饰符,它必须与$each修饰符一起出现。
{
$push: {
<field>: {
$each: [ <value1>, <value2>, ... ],
$position: <num>
}
}
}
在版本 3.6 中更改:$position可以接受负数组索引值以指示从末尾开始(从(但不包括)数组的最后一个元素开始)的位置。
<num>
根据从零开始的索引指示数组中的位置:
从数组的开头开始,非负数对应于数组中的位置。如果
<num>
的值大于或等于数组的长度,则$position修饰符无效,而$push将元素添加到数组的末尾。负数对应于数组中的位置,从(但不包括)数组的最后一个元素开始计数。例如,
-1
表示数组中最后一个元素之前的位置。如果您在$each数组中指定了多个元素,则最后添加的元素位于末尾的指定位置。如果<num>
的绝对值大于或等于数组的长度,则$push将元素添加到数组的开头。
Examples
在数组的开头添加元素
考虑一个包含以下文档的集合students
:
{ "_id" : 1, "scores" : [ 100 ] }
以下操作更新scores
字段,以将元素50
,60
和70
添加到数组的开头:
db.students.update(
{ _id: 1 },
{
$push: {
scores: {
$each: [ 50, 60, 70 ],
$position: 0
}
}
}
)
该操作生成以下更新的文档:
{ "_id" : 1, "scores" : [ 50, 60, 70, 100 ] }
将元素添加到数组的中间
考虑一个包含以下文档的集合students
:
{ "_id" : 1, "scores" : [ 50, 60, 70, 100 ] }
以下操作更新scores
字段,以在2
的数组索引处添加元素20
和30
:
db.students.update(
{ _id: 1 },
{
$push: {
scores: {
$each: [ 20, 30 ],
$position: 2
}
}
}
)
该操作生成以下更新的文档:
{ "_id" : 1, "scores" : [ 50, 60, 20, 30, 70, 100 ] }
使用负索引将元素添加到数组
在版本 3.6 中更改:$position可以接受负数组索引值以指示从末尾开始(从(但不包括)数组的最后一个元素开始)的位置。例如,-1
表示数组中最后一个元素之前的位置。
考虑一个包含以下文档的集合students
:
{ "_id" : 1, "scores" : [ 50, 60, 20, 30, 70, 100 ] }
以下操作为$position指定-2
,以便在最后一个元素之前的两个位置添加90
,然后在最后一个元素之前的两个位置添加80
。
Important
对于负索引位置,如果在$each数组中指定多个元素,则最后添加的元素位于末尾的指定位置。
db.students.update(
{ _id: 1 },
{
$push: {
scores: {
$each: [ 90, 80 ],
$position: -2
}
}
}
)
该操作生成以下更新的文档:
{ "_id" : 1, "scores" : [ 50, 60, 20, 30, 90, 80, 70, 100 ] }