- Reference >
- Operators >
- Update Operators >
- Array Update Operators >
- $position
$position¶
On this page
Definition¶
- $position¶
2.6 新版功能.
The $position modifier specifies the location in the array at which the $push operator insert 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> } } }
The <num> is a non-negative number that corresponds to the position in the array, based on a zero-based index.
If the <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.
Examples¶
Add Elements at the Start of the Array¶
Consider a collection students that contains the following document:
{ "_id" : 1, "scores" : [ 100 ] }
The following operation updates the scores field to add the elements 50, 60 and 70 to the beginning of the array:
db.students.update(
{ _id: 1 },
{
$push: {
scores: {
$each: [ 50, 60, 70 ],
$position: 0
}
}
}
)
The operation results in the following updated document:
{ "_id" : 1, "scores" : [ 50, 60, 70, 100 ] }
Add Elements to the Middle of the Array¶
Consider a collection students that contains the following document:
{ "_id" : 1, "scores" : [ 50, 60, 70, 100 ] }
The following operation updates the scores field to add the elements 20 and 30 at the array index of 2:
db.students.update(
{ _id: 1 },
{
$push: {
scores: {
$each: [ 20, 30 ],
$position: 2
}
}
}
)
The operation results in the following updated document:
{ "_id" : 1, "scores" : [ 50, 60, 20, 30, 70, 100 ] }