I'd like to have push add at the beginning of my set rather than appended to the end when I do a mongo $push.
Is it possible to do an atomic push update that adds elements as the first rather than the last?
2014 update: yes you can.
Description. In MongoDB, the $push operator is used to appends a specified value to an array. If the mentioned field is absent in the document to update, the $push operator add it as a new field and includes mentioned value as its element.
If the value is an array, $push appends the whole array as a single element. To add each element of the value separately, use the $each modifier with $push . For an example, see Append a Value to Arrays in Multiple Documents. For a list of modifiers available for $push , see Modifiers.
Update Nested Arrays in Conjunction with $[]The $[<identifier>] filtered positional operator, in conjunction with the $[] all positional operator, can be used to update nested arrays. The following updates the values that are greater than or equal to 8 in the nested grades. questions array if the associated grades.
To project, or return, an array element from a read operation, see the $ projection operator instead. To update all elements in an array, see the all positional operator $[] instead. To update all elements that match an array filter condition or conditions, see the filtered positional operator instead $[<identifier>] .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With