ANNOUNCEMENT: Voyage AI joins MongoDB to power more accurate and trustworthy AI applications on Atlas.
Learn more
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.

$pop 演算子の形式は次のとおりです。

{ $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.

MongoDB 5.0 以降、$popなどの更新演算子を空のオペランド式({ })と併用しても、mongod でエラーが発生しなくなりました。空の更新を使用すると変更は一切されず、oplog エントリも作成されません(操作は実行されません)。

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

次のドキュメントを 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 ] }

以下も参照してください。

項目一覧