Update quantity in MongoDB based on two conditions?

To update quantity in MongoDB based on two conditions, use the update() method with multiple filter criteria. Combine document-level and array element conditions to target specific nested objects.

Syntax

db.collection.update(
    { 
        "documentField": "value",
        "arrayField.nestedField": "arrayValue" 
    },
    { $set: { "arrayField.$.targetField": newValue } }
);

Sample Data

db.demo605.insertMany([
    {
        _id: 1,
        "Information": [
            {
                "id": "Product-1",
                "Quantity": 50
            },
            {
                "id": "Product-2", 
                "Quantity": 100
            }
        ]
    },
    {
        _id: 2,
        "Information": [
            {
                "id": "Product-1",
                "Quantity": 30
            },
            {
                "id": "Product-2",
                "Quantity": 40
            }
        ]
    }
]);
{
    "acknowledged": true,
    "insertedIds": [1, 2]
}

View Sample Data

db.demo605.find();
{ "_id": 1, "Information": [
    { "id": "Product-1", "Quantity": 50 },
    { "id": "Product-2", "Quantity": 100 }
] }
{ "_id": 2, "Information": [
    { "id": "Product-1", "Quantity": 30 },
    { "id": "Product-2", "Quantity": 40 }
] }

Example: Update Based on Two Conditions

Update quantity to 1000 for Product-1 in document with _id: 1 ?

db.demo605.update(
    { 
        _id: 1, 
        "Information.id": "Product-1" 
    },
    { $set: { "Information.$.Quantity": 1000 } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

db.demo605.find().pretty();
{
    "_id": 1,
    "Information": [
        {
            "id": "Product-1",
            "Quantity": 1000
        },
        {
            "id": "Product-2", 
            "Quantity": 100
        }
    ]
}
{
    "_id": 2,
    "Information": [
        {
            "id": "Product-1",
            "Quantity": 30
        },
        {
            "id": "Product-2",
            "Quantity": 40
        }
    ]
}

Key Points

  • The first condition _id: 1 matches the specific document
  • The second condition "Information.id": "Product-1" matches the array element
  • The $ positional operator targets the matched array element
  • Only Product-1 in document _id: 1 gets updated, other documents remain unchanged

Conclusion

Use multiple conditions in the filter criteria combined with the $ positional operator to update specific array elements. This approach ensures precise targeting when dealing with nested document structures.

Updated on: 2026-03-15T03:48:51+05:30

260 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements