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 :-)

4 comments:

  1. I agree. You have made the nice blogs with the great info in the contents.
    http://mediaonlines.com/

    ReplyDelete
  2. On your website, you shouldn’t use Google Tag Manager.
    xenforo forums

    ReplyDelete
  3. Canada Sex Toys
    Loved your blog page!!!The stuff that you have remarked up here is superbly wonderful and I vigorously thank you for the same...

    ReplyDelete