$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.将值-1传递给$pop以移除数组中的第一个元素,将值1传递给$pop以移除数组中的最后一个元素。

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行为

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>将保留一个空数组。

Examples示例

Remove the First Item of an Array删除数组的第一项

Given the following document in a collection students:students集合中提供以下文件:

{ _id: 1, scores: [ 8, 9, 10 ] }

The following example removes the first element (8) in the scores array:以下示例删除了scores数组中的第一个元素(8):

db.students.update( { _id: 1 }, { $pop: { scores: -1 } } )

After the operation, the updated document has the first item 8 removed from its scores array:操作完成后,更新后的文档将从其scores数组中删除第一项8

{ _id: 1, scores: [ 9, 10 ] }

Remove the Last Item of an Array删除数组的最后一项

Given the following document in a collection students:students集合中提供以下文档:

{ _id: 1, scores: [ 9, 10 ] }

The following example removes the last element (10) in the scores array by specifying 1 in the $pop expression:以下示例通过在$pop表达式中指定1来删除scores数组中的最后一个元素(10):

db.students.update( { _id: 1 }, { $pop: { scores: 1 } } )

After the operation, the updated document has the last item 10 removed from its scores array:操作完成后,更新后的文档将从其scores数组中删除最后一项10

{ _id: 1, scores: [ 9 ] }