Modify an element of an array in 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 :-)