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 a specific MongoDB document in array with set and positional operator?
To update a specific document in an array, use MongoDB's $set operator with the positional $ operator. The $ operator identifies the matched array element, while $set modifies the specified field within that element.
Syntax
db.collection.updateOne(
{ "arrayField.fieldName": "matchValue" },
{ $set: { "arrayField.$.fieldToUpdate": "newValue" } }
);
Sample Data
Let us create a collection with documents ?
db.demo462.insertOne({
"id": 1,
"DueDateDetails": [
{
"Name": "David",
"Age": 21,
"CountryName": ["US", "UK"]
},
{
"Name": "Chris",
"Age": 23,
"CountryName": ["UK"]
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e7f6c59cb66ccba22cc9dce")
}
Display all documents from the collection ?
db.demo462.find().pretty();
{
"_id": ObjectId("5e7f6c59cb66ccba22cc9dce"),
"id": 1,
"DueDateDetails": [
{
"Name": "David",
"Age": 21,
"CountryName": ["US", "UK"]
},
{
"Name": "Chris",
"Age": 23,
"CountryName": ["UK"]
}
]
}
Example: Update Array Element with $set and Positional $
Update Chris's CountryName field to "AUS" ?
db.demo462.updateOne(
{ id: 1, "DueDateDetails.Name": "Chris" },
{ $set: { "DueDateDetails.$.CountryName": "AUS" } }
);
{ "acknowledged": true, "matchedCount": 1, "modifiedCount": 1 }
Verify Result
Display the updated document ?
db.demo462.find().pretty();
{
"_id": ObjectId("5e7f6c59cb66ccba22cc9dce"),
"id": 1,
"DueDateDetails": [
{
"Name": "David",
"Age": 21,
"CountryName": ["US", "UK"]
},
{
"Name": "Chris",
"Age": 23,
"CountryName": "AUS"
}
]
}
Key Points
- The
$operator matches the first array element that satisfies the query condition. -
$setreplaces the entire field value ? Chris's CountryName changed from an array to a string. - Use dot notation
"arrayField.$.fieldName"to target specific fields within matched array elements.
Conclusion
The combination of $set and positional $ operator provides precise control for updating specific documents within MongoDB arrays. The $ identifies the matched element, while $set modifies the target field.
Advertisements
