

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Update array in MongoDB document by variable index?
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" ] }
- Related Questions & Answers
- Update object at specific Array Index in MongoDB?
- Update MongoDB variable value with variable itself?
- MongoDB query to update array object in index N?
- MongoDB query to update nested document
- Update only a single document in MongoDB
- MongoDB findOneAndUpdate() to update a single document
- MongoDB query to update the nested document?
- Update a specific MongoDB document in array with $set and positional $ operator?
- MongoDB query on nth element (variable index) of subdocument array
- Update Array element in MongoDB?
- Update only a specific value in a MongoDB document
- Update two separate arrays in a document with one update call in MongoDB?
- How do you update a MongoDB document while replacing the entire document?
- How to update the _id of a MongoDB Document?
- Update a single list item of a MongoDB document?
Advertisements