Can you have mongo $push prepend instead of append?

As of MongoDB v2.5.3, there is a new $position operator that you can include along with the $each operator as part of your $push query to specify the location in the array at which you would like to insert a value.

Here’s an example from the docs page 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
                                       }
                             }
                    }
                  )

Reference: http://docs.mongodb.org/master/reference/operator/update/position/#up._S_position

Leave a Comment