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

$position(更新演算子)

$position

The $position modifier specifies the location in the array at which the $push operator inserts elements. Without the $position modifier, the $push operator inserts elements to the end of the array. See $push modifiers for more information.

To use the $position modifier, it must appear with the $each modifier.

{
$push: {
<field>: {
$each: [ <value1>, <value2>, ... ],
$position: <num>
}
}
}

<num> ゼロベースの配列インデックス(位置)に基づいて、配列内の位置を示します。

  • A non-negative number corresponds to the position in the array, starting from the beginning of the array. If the value of <num> is greater or equal to the length of the array, the $position modifier has no effect and $push adds elements to the end of the array.

  • 負の数は、配列の最終要素から数えた(ただし最後の要素は含まない)配列内の位置に対応します。たとえば、-1 は配列の最終要素の直前の位置を示します。$each 配列に複数の要素を指定した場合、最後に追加された要素は末尾から指定された位置に配置されます。<num> の絶対値が配列の長さ以上の場合、$push は配列の先頭に要素を追加します。

MongoDB 5.0 以降、更新演算子では名前が文字列ベースのドキュメントフィールドを辞書順に処理します。数値名のフィールドは、数値順に処理されます。詳細については、「更新演算子の動作」を参照してください。

students コレクションを次のように作成します。

db.students.insertOne( { "_id" : 1, "scores" : [ 100 ] } )

次の操作では、scores フィールドをアップデートして、要素 506070 を配列の先頭に追加します。

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 の配列インデックス(位置)に要素 2030 を追加します。

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 ] }
このページを評価

項目一覧