Manipulating subdocuments in MongoDB

To manipulate subdocuments in MongoDB, use dot notation to target specific fields within embedded documents or arrays. The $ positional operator helps update elements that match query conditions.

Syntax

db.collection.update(
    { "arrayField.field": "matchValue" },
    { $operation: { "arrayField.$.targetField": value } }
);

Create Sample Data

db.demo378.insertOne({
    Name: "Chris",
    details: [
        { id: 101, Score: 56 },
        { id: 102, Score: 78 }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e5a758a2ae06a1609a00b0f")
}

Example: Update Subdocument Field

Let's decrease the Score of the subdocument with id 102 by 8 points ?

db.demo378.update(
    { Name: "Chris", "details.id": 102 },
    { $inc: { "details.$.Score": -8 } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

db.demo378.find();
{
    "_id": ObjectId("5e5a758a2ae06a1609a00b0f"),
    "Name": "Chris",
    "details": [
        { "id": 101, "Score": 56 },
        { "id": 102, "Score": 70 }
    ]
}

How It Works

  • "details.id": 102 matches the subdocument where id equals 102
  • "details.$.Score" targets the Score field of the matched subdocument using the $ positional operator
  • $inc: -8 decrements the Score value by 8

Conclusion

Use dot notation with the $ positional operator to manipulate specific subdocuments in arrays. The $ operator references the first matched array element, allowing precise updates to nested document fields.

Updated on: 2026-03-15T02:44:18+05:30

210 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements