MongoDB query to set a sub item in an array?

To set a sub item in an array in MongoDB, use the $ positional operator which identifies the first array element that matches the query condition and allows you to update specific fields within that element.

Syntax

db.collection.update(
    {"arrayField.subField": "matchValue"},
    {$set: {"arrayField.$.subField": "newValue"}}
);

Sample Data

Let us create a collection with product documents ?

db.demo22.insertOne({
    ProductId: 101,
    ProductDetails: [
        {
            ProductFirstPrice: "35",
            ProductSecondPrice: "75"
        },
        {
            ProductFirstPrice: "",
            ProductSecondPrice: ""
        },
        {
            ProductFirstPrice: "78",
            ProductSecondPrice: "24"
        }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e14c0b422d07d3b95082e70")
}

Display all documents from the collection ?

db.demo22.find().pretty();
{
    "_id": ObjectId("5e14c0b422d07d3b95082e70"),
    "ProductId": 101,
    "ProductDetails": [
        {
            "ProductFirstPrice": "35",
            "ProductSecondPrice": "75"
        },
        {
            "ProductFirstPrice": "",
            "ProductSecondPrice": ""
        },
        {
            "ProductFirstPrice": "78",
            "ProductSecondPrice": "24"
        }
    ]
}

Example: Update Sub Item in Array

Update the ProductFirstPrice from "35" to an empty string using the positional operator ?

db.demo22.update(
    {"ProductDetails.ProductFirstPrice": "35"},
    {$set: {"ProductDetails.$.ProductFirstPrice": ""}}
);
WriteResult({"nMatched": 1, "nUpserted": 0, "nModified": 1})

Verify Result

Check the updated document ?

db.demo22.find().pretty();
{
    "_id": ObjectId("5e14c0b422d07d3b95082e70"),
    "ProductId": 101,
    "ProductDetails": [
        {
            "ProductFirstPrice": "",
            "ProductSecondPrice": "75"
        },
        {
            "ProductFirstPrice": "",
            "ProductSecondPrice": ""
        },
        {
            "ProductFirstPrice": "78",
            "ProductSecondPrice": "24"
        }
    ]
}

Conclusion

The $ positional operator efficiently updates specific sub items in arrays by matching the query condition and modifying only the first matching array element, making it ideal for targeted updates in nested document structures.

Updated on: 2026-03-15T02:28:26+05:30

328 Views

Advertisements