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 in array with a specific key in MongoDB
To update an object in an array with a specific key in MongoDB, use the $ positional operator with dot notation to match and update the desired array element based on a specific field value.
Syntax
db.collection.update(
{ "arrayName.keyField": "matchValue" },
{ $set: { "arrayName.$.updateField": "newValue" } }
);
Sample Data
Let us first create a collection with sample documents ?
db.demo419.insertOne({
"ProductInformation": [
{
"ProductName": "Product-1",
"ProductPrice": 500
},
{
"ProductName": "Product-2",
"ProductPrice": 600
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e724762b912067e57771ae8")
}
Display all documents from the collection ?
db.demo419.find();
{
"_id": ObjectId("5e724762b912067e57771ae8"),
"ProductInformation": [
{ "ProductName": "Product-1", "ProductPrice": 500 },
{ "ProductName": "Product-2", "ProductPrice": 600 }
]
}
Example: Update Product Price by Product Name
Update the price of "Product-1" from 500 to 1250 ?
db.demo419.update(
{ "ProductInformation.ProductName": "Product-1" },
{ $set: { "ProductInformation.$.ProductPrice": 1250 } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
Display the updated document ?
db.demo419.find();
{
"_id": ObjectId("5e724762b912067e57771ae8"),
"ProductInformation": [
{ "ProductName": "Product-1", "ProductPrice": 1250 },
{ "ProductName": "Product-2", "ProductPrice": 600 }
]
}
Key Points
- The
$operator identifies the first array element matching the query condition. - Use dot notation
arrayName.$.fieldNameto update specific fields within the matched object. - Only the first matching array element gets updated if multiple elements match the criteria.
Conclusion
The $ positional operator combined with $set allows precise updates to objects within arrays by matching specific key values. This approach efficiently updates array elements without affecting other array items.
Advertisements
