定義
動作
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 ] } )
次の例では、10 scores1式で$pop を指定して、 配列から 最後の 要素 を削除します。
db.students.updateOne( { _id: 10 }, { $pop: { scores: 1 } } )
最後の要素 10 が scores 配列から削除されました。
{ _id: 10, scores: [ 9 ] }