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

  • $elemMatch finds the array element where Name equals "David"
  • $ positional operator identifies the matched array element's position
  • $set updates the Age field 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.

Updated on: 2026-03-15T01:28:00+05:30

280 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements