定义
行为
从 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 ] }