how do i add a value to the top of an array in mongodb?
say i have this document in my mongo collection:
{ "colors" : [ "red", "green", "blue" ] }
how do i add "yellow" to the front of the list?
when i do:
{$push:{colors:"yellow"}}
i'd get this:
{ "colors" : [ "red", "green", "blue", "yellow" ] }
i want this:
{ "colors" : [ "yellow", "red", "green", "blue"] }
thanks in advance!
The $push operator appends a specified value to an array. The $push operator has the form: { $push: { <field1>: <value1>, ... } } To specify a <field> in an embedded document or in an array, use dot notation.
In MongoDB, the $inc operator is used to increment the value of a field by a specified amount. The $inc operator adds as a new field when the specified field does not exist, and sets the field to the specified amount. The $inc accepts positive and negative value as an incremental amount.
You can use the updateOne() or updateMany() methods to add, update, or remove array elements based on the specified criteria. It is recommended to use the updateMany() method to update multiple arrays in a collection.
To add field or fields to embedded documents (including documents in arrays) use the dot notation. See example. To add an element to an existing array field with $addFields , use with $concatArrays .
For anybody new to this, MongoDB 2.6+ supports the $position
operator, which can be used to achieve the desired effect. The benefit here being that you don't need to return your entire document array, update it locally and save it - the $position
operator means things can be done atomically.
You need to use it in conjunction with $each
:
$push: { colors: { $each: ['yellow'], $position: 0 } }
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