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 key value where another key equals some value in MongoDB?
To update a key value where another key equals a specific value in MongoDB arrays, use $elemMatch to match the array element and $set with the positional operator $ to update the matched element.
Syntax
db.collection.update(
{ "arrayField": { "$elemMatch": { "matchKey": "matchValue" } } },
{ "$set": { "arrayField.$.updateKey": "newValue" } }
);
Sample Data
Let us first create a collection with documents ?
db.keyValueDemo.insertOne({
"_id": new ObjectId(),
"CustomerDetails": [
{
"Name": "Chris",
"Age": 24
},
{
"Name": "Robert",
"Age": 29
},
{
"Name": "David",
"Age": 35
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5cefcf36ef71edecf6a1f6bf")
}
Following is the query to display all documents from a collection with the help of find() method ?
db.keyValueDemo.find().pretty();
Output
{
"_id": ObjectId("5cefcf36ef71edecf6a1f6bf"),
"CustomerDetails": [
{
"Name": "Chris",
"Age": 24
},
{
"Name": "Robert",
"Age": 29
},
{
"Name": "David",
"Age": 35
}
]
}
Example: Update Age Where Name Equals "David"
Here is the query to update key value where different key equals some value ?
db.keyValueDemo.update(
{ "CustomerDetails": { "$elemMatch": { "Name": "David" } } },
{ "$set": { "CustomerDetails.$.Age": 56 } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Let us check the document once again ?
db.keyValueDemo.find().pretty();
Output
{
"_id": ObjectId("5cefcf36ef71edecf6a1f6bf"),
"CustomerDetails": [
{
"Name": "Chris",
"Age": 24
},
{
"Name": "Robert",
"Age": 29
},
{
"Name": "David",
"Age": 56
}
]
}
How It Works
-
$elemMatchfinds the array element whereNameequals "David" -
$positional operator identifies the matched array element's position -
$setupdates theAgefield of that specific element
Conclusion
Use $elemMatch with the positional operator $ to update specific fields in array elements based on matching criteria. This approach ensures only the targeted array element is modified while preserving other elements unchanged.
Advertisements
