To update array in MongoDB document by variable index, use the below syntax. Here, yourIndexValue in the index value, where yourIndexVariableName is the variable name for index −
var yourIndexVariableName= yourIndexValue,
anyVariableName= { "$set": {} };
yourVariableName["$set"]["yourFieldName."+yourIndexVariableName] = "yourValue";
db.yourCollectionName.update({ "_id": yourObjectId}, yourVariableName);Let us first create a collection with documents −
> db.updateByVariableDemo.insertOne({"StudentSubjects":["MySQL","Java","SQL Server","PL/SQL"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd553c37924bb85b3f4893a")
}Following is the query to display all documents from a collection with the help of find() method −
> db.updateByVariableDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5cd553c37924bb85b3f4893a"),
"StudentSubjects" : [
"MySQL",
"Java",
"SQL Server",
"PL/SQL"
]
}Following is the query to update array in MongoDB document by variable index −
> var indexValue = 1,
... valueToUpdate= { "$set": {} };
> valueToUpdate["$set"]["StudentSubjects."+indexValue] = "MongoDB";
MongoDB
> db.updateByVariableDemo.update({ "_id": ObjectId("5cd553c37924bb85b3f4893a") }, valueToUpdate)
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })Let us display the documents once again −
> db.updateByVariableDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5cd553c37924bb85b3f4893a"),
"StudentSubjects" : [
"MySQL",
"MongoDB",
"SQL Server",
"PL/SQL"
]
}