OPTIONS

$position

$position

New in version 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 operator for more information.

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

db.collection.update( <query>,
                      { $push: {
                                  <field>: {
                                             $each: [ <value1>, <value2>, ... ],
                                             $position: <num>
                                  }
                               }
                      }
                    )

The <num> is either a zero or a positive number that correspond to position in the array, based on a zero-based index. If the number is greater or equal to the length of the array, the $position modifier has no effect and the operator 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 and 60 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 ] }