定義
$positionThe
$positionmodifier specifies the location in the array at which the$pushoperator inserts elements. Without the$positionmodifier, the$pushoperator inserts elements to the end of the array. See $push modifiers for more information.To use the
$positionmodifier, it must appear with the$eachmodifier.{ $push: { <field>: { $each: [ <value1>, <value2>, ... ], $position: <num> } } } <num>ゼロベースの配列インデックス(位置)に基づいて、配列内の位置を示します。
動作
MongoDB 5.0 以降、更新演算子では名前が文字列ベースのドキュメントフィールドを辞書順に処理します。数値名のフィールドは、数値順に処理されます。詳細については、「更新演算子の動作」を参照してください。
例
配列の先頭に要素を追加する
students コレクションを次のように作成します。
db.students.insertOne( { "_id" : 1, "scores" : [ 100 ] } )
次の操作では、scores フィールドをアップデートして、要素 50、60、70 を配列の先頭に追加します。
db.students.updateOne( { _id: 1 }, { $push: { scores: { $each: [ 50, 60, 70 ], $position: 0 } } } )
この操作により、次のドキュメントが更新されます。
{ "_id" : 1, "scores" : [ 50, 60, 70, 100 ] }
配列の中央に要素を追加する
students コレクションにドキュメントを追加します。
db.students.insertOne( { "_id" : 2, "scores" : [ 50, 60, 70, 100 ] } )
次の操作では、scores フィールドを更新して 2 の配列インデックス(位置)に要素 20 と 30 を追加します。
db.students.updateOne( { _id: 2 }, { $push: { scores: { $each: [ 20, 30 ], $position: 2 } } } )
この操作により、次のドキュメントが更新されます。
{ "_id" : 2, "scores" : [ 50, 60, 20, 30, 70, 100 ] }
負の配列インデックス(位置)を使って配列に要素を追加する
$position can accept a negative array index (position) value to indicate the position starting from the end, counting from (but not including) the last element of the array. For example, -1 indicates the position just before the last element in the array.
次のドキュメントを students コレクションに追加します。
db.students.insertOne( { "_id" : 3, "scores" : [ 50, 60, 20, 30, 70, 100 ] } )
The following operation specifies -2 for the $position to add 90 at the position two places before the last element, and then 80 at the position two places before the last element.
重要
配列のインデックス(位置)が負の場合、$each 配列に複数の要素を指定すると、最後に追加された要素は末尾から指定された位置に配置されます。
db.students.updateOne( { _id: 3 }, { $push: { scores: { $each: [ 90, 80 ], $position: -2 } } } )
この操作により、次のドキュメントが更新されます。
{ "_id" : 3, "scores" : [ 50, 60, 20, 30, 90, 80, 70, 100 ] }