$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 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>,请使用点表示法

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, mongod no longer raises an error when you use an update operator like $pop with an empty operand expression ( { } ). 从MongoDB 5.0开始,当使用带有空操作数表达式({ })的更新运算符(如$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 scores array:第一个元素8已从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 scores array:最后一个元素10已从scores数组中删除:

{ _id: 10, scores: [ 9 ] }
←  $addToSet$pull →