title: MongoDB: How do I update a single subelement in an array, referenced by the index within the array?
body: <p>I'm trying to update a single subelement contained within an array in a mongodb document. I want to reference the field using its array index (elements within the array don't have any fields that I can guarantee will be unique identifiers). Seems like this should be easy to do, but I can't figure out the syntax.</p>
  
  <p>Here's what I want to do in pseudo-json.</p>
  
  <p>Before:</p>
  
  <pre><code>{
    _id : ...,
    other_stuff ... ,
    my_array : [
      { ... old content A ... },
      { ... old content B ... },
      { ... old content C ... }
    ]
  }
  </code></pre>
  
  <p>After:</p>
  
  <pre><code>{
    _id : ...,
    other_stuff ... ,
    my_array : [
      { ... old content A ... },
      { ... NEW content B ... },
      { ... old content C ... }
    ]
  }
  </code></pre>
  
  <p>Seems like the query should be something like this:</p>
  
  <pre><code>//pseudocode
  db.my_collection.update(
    {_id: ObjectId(document_id), my_array.1 : 1 },
    {my_array.$.content: NEW content B }
  )
  </code></pre>
  
  <p>But this doesn't work. I've spent way too long searching the mongodb docs, and trying different variations on this syntax (e.g. using <code>$slice</code>, etc.). I can't find any clear explanation of how to accomplish this kind of update in MongoDB.</p>