Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you have mongo $push prepend instead of append?

Tags:

arrays

mongodb

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.

like image 802
MonkeyBonkey Avatar asked Apr 12 '12 21:04

MonkeyBonkey


People also ask

What does $Push do in MongoDB?

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.

How do I append to an array in MongoDB?

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.

How do I update a nested array in MongoDB?

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.

How do you update an array of objects in MongoDB?

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>] .


1 Answers

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

like image 140
Ted Avery Avatar answered Oct 04 '22 22:10

Ted Avery