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
MongoDB query to update array object in index N?
To update an array object at a specific index in MongoDB, use the $ positional operator with dot notation. The $ operator identifies the matched array element, allowing you to update its nested fields.
Syntax
db.collection.update(
{"arrayField.matchingField": "value"},
{$set: {"arrayField.$.nestedField": "newValue"}}
)
Sample Data
db.demo489.insertOne({
details: [
{
id: 101,
"Info1": {
"StudentName": "Chris"
},
"Info2": {
"TeacherName": "David"
}
},
{
id: 102,
"Info1": {
"StudentName": "Carol"
},
"Info2": {
"TeacherName": "Mike"
}
}
]
})
{
"acknowledged": true,
"insertedId": ObjectId("5e8356e0b0f3fa88e22790ba")
}
Display all documents from the collection ?
db.demo489.find()
{
"_id": ObjectId("5e8356e0b0f3fa88e22790ba"),
"details": [
{
"id": 101,
"Info1": {"StudentName": "Chris"},
"Info2": {"TeacherName": "David"}
},
{
"id": 102,
"Info1": {"StudentName": "Carol"},
"Info2": {"TeacherName": "Mike"}
}
]
}
Example: Update Array Object by Matching Field
Update the array object where id is 102 ?
db.demo489.update(
{"details.id": 102},
{
$set: {
"details.$.Info1.StudentName": "Robert",
"details.$.Info2.TeacherName": "John",
"details.$.CountryName": "US"
}
}
)
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
db.demo489.find().pretty()
{
"_id": ObjectId("5e8356e0b0f3fa88e22790ba"),
"details": [
{
"id": 101,
"Info1": {
"StudentName": "Chris"
},
"Info2": {
"TeacherName": "David"
}
},
{
"id": 102,
"Info1": {
"StudentName": "Robert"
},
"Info2": {
"TeacherName": "John"
},
"CountryName": "US"
}
]
}
Key Points
- The
$operator matches the first array element that satisfies the query condition - Use dot notation to access nested fields within the matched array element
- Multiple fields can be updated in a single operation using
$set
Conclusion
The positional operator $ combined with dot notation provides an efficient way to update specific array objects in MongoDB. This approach allows precise modifications to nested document fields within arrays.
Advertisements
