对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

$pop(更新操作符)

$pop

The $pop operator removes the first or last element of an array. Pass $pop a value of -1 to remove the first element of an array and 1 to remove the last element in an array.

The $pop operator has the form:

{ $pop: { <field>: <-1 | 1>, ... } }

要在嵌入式文档或数组中指定 <field>,请使用点符号。

从 MongoDB 5.0 开始,更新操作符按字典顺序处理具有基于字符串的名称的文档字段。具有数字名称的字段按数字顺序处理。详情请参阅更新操作符行为

The $pop operation fails if the <field> is not an array.

If the $pop operator removes the last item in the <field>, the <field> will then hold an empty array.

从MongoDB5.0 开始,当您将 等更新操作符符与空操作数表达式()mongod $pop一起使用时,{ } 不再引发错误。空更新不会导致任何更改,也不会创建oplog条目(意味着该操作为“不操作”)。

创建 students 集合:

db.students.insertOne( { _id: 1, scores: [ 8, 9, 10 ] } )

以下示例从scores数组中删除第一个元素 8:

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

第一个元素 8 已从 scores 数组中删除:

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

将以下文档添加到 students 集合中:

db.students.insertOne( { _id: 10, scores: [ 9, 10 ] } )

以下示例通过在 表达式中指定 ,从 大量中删除最后一个元素 10scores1$pop

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

最后一个元素 10 已从scores数组中删除:

{ _id: 10, scores: [ 9 ] }
给本页内容打分

在此页面上