Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Update object at specific Array Index in MongoDB?
To update object at specific array index in MongoDB, use the $set operator with dot notation to target the exact position in nested arrays. Specify the array path with numeric indices to access objects at specific locations.
Syntax
db.collection.update(
{ "field": "value" },
{ $set: { "arrayName.index1.index2.fieldName": "newValue" } }
);
Sample Data
Let us first create a collection with nested array structure:
db.updateObjectDemo.insertOne({
id: 101,
"StudentDetails": [
[
{ "StudentName": "John" },
{ "StudentName": "Chris" }
],
[
{ "StudentName": "Carol" },
{ "StudentName": "David" }
]
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5ccdcd9b685b30d09a7111e0")
}
Display the current document structure:
db.updateObjectDemo.find().pretty();
{
"_id": ObjectId("5ccdcd9b685b30d09a7111e0"),
"id": 101,
"StudentDetails": [
[
{ "StudentName": "John" },
{ "StudentName": "Chris" }
],
[
{ "StudentName": "Carol" },
{ "StudentName": "David" }
]
]
}
Example: Update Object at Index [1,1]
Update the StudentName at position [1,1] from "David" to "Mike":
db.updateObjectDemo.update(
{ "id": 101 },
{ $set: { "StudentDetails.1.1.StudentName": "Mike" } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
Check if the object at index [1,1] has been updated:
db.updateObjectDemo.find().pretty();
{
"_id": ObjectId("5ccdcd9b685b30d09a7111e0"),
"id": 101,
"StudentDetails": [
[
{ "StudentName": "John" },
{ "StudentName": "Chris" }
],
[
{ "StudentName": "Carol" },
{ "StudentName": "Mike" }
]
]
}
Key Points
- Use dot notation with numeric indices to access nested array elements
-
StudentDetails.1.1targets the second array's second element - Array indexing starts from 0 in MongoDB
Conclusion
Use $set with dot notation and numeric indices to update objects at specific positions in nested arrays. The syntax arrayName.index1.index2.fieldName provides precise control over which element to modify.
Advertisements
