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 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: 1matches 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.
Advertisements
