On this page
$pop
在本页面
Definition
$pop运算符的格式为:
{ $pop: { <field>: <-1 | 1>, ... } }
要在嵌入式文档或数组中指定<field>
,请使用dot notation。
Behavior
如果<field>
不是数组,则$pop操作失败。
如果$pop运算符删除了<field>
中的最后一项,则<field>
将保留一个空数组。
Examples
删除数组的第一项
给定集合students
中的以下文档:
{ _id: 1, scores: [ 8, 9, 10 ] }
下面的示例删除scores
数组中的* first *元素(8
):
db.students.update( { _id: 1 }, { $pop: { scores: -1 } } )
操作完成后,更新后的文档将第一项8
从其scores
数组中删除:
{ _id: 1, scores: [ 9, 10 ] }
删除数组的最后一项
给定集合students
中的以下文档:
{ _id: 1, scores: [ 9, 10 ] }
下面的示例通过在$pop表达式中指定1
来删除scores
数组中的* last *元素(10
):
db.students.update( { _id: 1 }, { $pop: { scores: 1 } } )
操作完成后,更新后的文档将最后一个项目10
从其scores
数组中删除:
{ _id: 1, scores: [ 9 ] }