AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。
Docs Menu

$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 ] } )

次の例では、10 scores1式で$pop を指定して、 配列から 最後の 要素 を削除します。

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

最後の要素 10 が scores 配列から削除されました。

{ _id: 10, scores: [ 9 ] }
このページを評価

項目一覧