šŸ“š Blog Archive

Modify an element of an array in MongoDB

· Miguel Parramón · blogger

Tags: dev diary, MongoDB

Let’s say you have a document in MongoDB like so:

{ ā€œapple_pieā€ : { ā€œingredientsā€ : [ ā€œflourā€, ā€œorangeā€, ā€œbutterā€, ā€œsugarā€ ] } }

And you see that you’ve made a mistake there: one of the elements of the ingredients array should be changed, to apple. But how?

Turns out there’s an operator called ā€$ā€, which, in an update operation, identifies an element in an array, without having to know its positional value. We would use it in this case like so:

db.recipes.update( {ā€œapple_pie.ingredientsā€: ā€œorangeā€}, { ā€œ$setā€: {ā€œapple_pie.ingredients.$ā€: ā€œappleā€} } )

Once we have selected an element on the query side of the update, we can refer to it with $. So, this update operation means: ā€œselect the array element named orange, and set it to appleā€.Ā 

You can find more info about this operator on the mongoDB docs, but I hope this post helps you find your way if you google for this problem :-)

ęŸ„ēœ‹åŽŸę–‡ →