On this page本页内容
$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 and 1
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>
,请使用点表示法。
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条目(这意味着该操作是无操作)。
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 ] }
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 ] }