MongoDB: How do I update a single subelement in an array, referenced by the index within the array?

As expected, the query is easy once you know how. Here's the syntax, in python:

db["my_collection"].update(
    { "_id": ObjectId(document_id) },
    { "$set": { 'documents.'+str(doc_index)+'.content' : new_content_B}}
)

Update of an array element referenced by an index (e.g. 1 ) in Mongo Shell can also be done by directly indicating the index value:

db.my_collection.update(
    {_id : "document_id"},
    {$set : {"my_array.1.content" : "New content B"}}
)

In mongo style, using '$' positional operator. Check out this link for details.

db.my_collection.update(
  {_id: ObjectId(document_id), my_array.1 : 1 },
  { $set: { "my_array.$.content" : "NEW content B" } }
)

Tags:

Arrays

Mongodb