Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do i add a value to the top of an array in mongodb?

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!

like image 922
Khon Lieu Avatar asked Oct 28 '11 23:10

Khon Lieu


People also ask

How do I add a value to an array in MongoDB?

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.

How do I increment a variable in MongoDB?

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.

How do you update an array element in MongoDB?

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.

How do I add a field value in MongoDB?

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 .


1 Answers

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 } }
like image 86
Tom Spencer Avatar answered Oct 19 '22 02:10

Tom Spencer