$pop
On this page本页内容
Definition定义
$pop
-
The$pop
operator removes the first or last element of an array.$pop
运算符删除数组的第一个或最后一个元素。Pass传递$pop
a value of-1
to remove the first element of an array and1
to remove the last element in an array.$pop
值-1
以移除数组的第一个元素,传递1
以移除数组中的最后一个元素。The$pop
operator has the form:$pop
运算符的形式如下:{ $pop: { <field>: <-1 | 1>, ... } }
To specify a要在嵌入文档或数组中指定<field>
in an embedded document or in an array, use dot notation.<field>
,请使用点表示法。
Behavior行为
Starting in MongoDB 5.0, update operators process document fields with string-based names in lexicographic order. 从MongoDB 5.0开始,更新运算符按照字典顺序处理具有基于字符串的名称的文档字段。Fields with numeric names are processed in numeric order. 具有数字名称的字段按数字顺序处理。See Update Operators Behavior for details.有关详细信息,请参阅更新运算符行为。
The 如果$pop
operation fails if the <field>
is not an array.<field>
不是数组,$pop
操作将失败。
If the 如果$pop
operator removes the last item in the <field>
, the <field>
will then hold an empty array.$pop
运算符删除了<field>
中的最后一项,则<field>
将保留一个空数组。
Starting in MongoDB 5.0, 从MongoDB 5.0开始,当您将mongod
no longer raises an error when you use an update operator like $pop
with an empty operand expression ( { }
). $pop
之类的更新运算符与空操作数表达式({ }
)一起使用时,mongod
不再引发错误。An empty update results in no changes and no oplog entry is created (meaning that the operation is a no-op).空更新不会导致任何更改,也不会创建oplog条目(这意味着该操作是无操作)。
Examples实例
Remove the First Item of an Array移除数组的第一项
Create the 创建students
collection:students
集合:
db.students.insertOne( { _id: 1, scores: [ 8, 9, 10 ] } )
The following example removes the first element, 8, from the 以下示例从scores
array:scores
数组中删除第一个元素8:
db.students.updateOne( { _id: 1 }, { $pop: { scores: -1 } } )
The first element, 8, has been removed from the 第一个元素8已从scores
array:scores
数组中删除:
{ _id: 1, scores: [ 9, 10 ] }
Remove the Last Item of an Array删除数组的最后一项
Add the following document to the 将以下文档添加到students
collection:students
集合中:
db.students.insertOne( { _id: 10, scores: [ 9, 10 ] } )
The following example removes the last element, 10, from the 以下示例通过在scores
array by specifying 1
in the $pop
expression:$pop
表达式中指定1
,从scores
数组中删除最后一个元素10
:
db.students.updateOne( { _id: 10 }, { $pop: { scores: 1 } } )
The last element, 10, has been removed from the 最后一个元素10已从scores
array:scores
数组中删除:
{ _id: 10, scores: [ 9 ] }