Update array in MongoDB document by variable index?

To update array in MongoDB document by variable index, use a JavaScript variable to dynamically construct the field path. This allows you to target specific array positions using a variable instead of hardcoding the index value.

Syntax

var indexVariable = yourIndexValue,
    updateObject = { "$set": {} };
updateObject["$set"]["arrayFieldName." + indexVariable] = "newValue";
db.collectionName.update({ "_id": ObjectId("...") }, updateObject);

Sample Data

Let us first create a collection with documents ?

db.updateByVariableDemo.insertOne({
    "StudentSubjects": ["MySQL", "Java", "SQL Server", "PL/SQL"]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5cd553c37924bb85b3f4893a")
}

Display the document using find() method ?

db.updateByVariableDemo.find().pretty();
{
    "_id": ObjectId("5cd553c37924bb85b3f4893a"),
    "StudentSubjects": [
        "MySQL",
        "Java", 
        "SQL Server",
        "PL/SQL"
    ]
}

Example: Update Array Element at Variable Index

Update the array element at index 1 (second position) using a variable ?

var indexValue = 1,
    valueToUpdate = { "$set": {} };
valueToUpdate["$set"]["StudentSubjects." + indexValue] = "MongoDB";
db.updateByVariableDemo.update(
    { "_id": ObjectId("5cd553c37924bb85b3f4893a") }, 
    valueToUpdate
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

Display the updated document ?

db.updateByVariableDemo.find().pretty();
{
    "_id": ObjectId("5cd553c37924bb85b3f4893a"),
    "StudentSubjects": [
        "MySQL",
        "MongoDB",
        "SQL Server", 
        "PL/SQL"
    ]
}

Key Points

  • Use string concatenation to build the field path dynamically: "arrayField." + indexVariable
  • Create an empty $set object first, then assign the field path using bracket notation
  • This approach is useful when the array index comes from user input or calculations

Conclusion

Variable index updates in MongoDB require JavaScript string concatenation to build the field path dynamically. This technique enables programmatic array updates when the target index is determined at runtime.

Updated on: 2026-03-15T01:13:29+05:30

430 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements