$pop
定義
動作
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.
MongoDB 5.0 以降、$pop
などの更新演算子を空のオペランド式(
{ }
)と併用しても、
mongod
でエラーが発生しなくなりました。空の更新を使用すると変更は一切されず、oplog エントリも作成されません(操作は実行されません)。
例
Remove the First Item of an Array
students
コレクションを次のように作成します。
db.students.insertOne( { _id: 1, scores: [ 8, 9, 10 ] } )
The following example removes the first element, 8, from the
scores
array:
db.students.updateOne( { _id: 1 }, { $pop: { scores: -1 } } )
The first element, 8, has been removed from the scores
array:
{ _id: 1, scores: [ 9, 10 ] }
Remove the Last Item of an Array
次のドキュメントを students
コレクションに追加します。
db.students.insertOne( { _id: 10, scores: [ 9, 10 ] } )
The following example removes the last element, 10, from the
scores
array by specifying 1
in the $pop
expression:
db.students.updateOne( { _id: 10 }, { $pop: { scores: 1 } } )
The last element, 10, has been removed from the scores
array:
{ _id: 10, scores: [ 9 ] }
以下も参照してください。