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
Decrement only a single value in MongoDB?
To decrement only a single value in MongoDB, use the $inc operator with a negative value. This allows you to decrease a numeric field by a specified amount while targeting only one document.
Syntax
db.collection.update(
{ field: "matchValue" },
{ $inc: { numericField: -decrementValue } }
);
Create Sample Data
db.decrementingOperationDemo.insertMany([
{ "ProductName": "Product-1", "ProductPrice": 756 },
{ "ProductName": "Product-2", "ProductPrice": 890 },
{ "ProductName": "Product-3", "ProductPrice": 994 },
{ "ProductName": "Product-4", "ProductPrice": 1000 }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cd7a8ae6d78f205348bc63c"),
ObjectId("5cd7a8b86d78f205348bc63d"),
ObjectId("5cd7a8c66d78f205348bc63e"),
ObjectId("5cd7a8d06d78f205348bc63f")
]
}
Display All Documents
db.decrementingOperationDemo.find().pretty();
{
"_id": ObjectId("5cd7a8ae6d78f205348bc63c"),
"ProductName": "Product-1",
"ProductPrice": 756
}
{
"_id": ObjectId("5cd7a8b86d78f205348bc63d"),
"ProductName": "Product-2",
"ProductPrice": 890
}
{
"_id": ObjectId("5cd7a8c66d78f205348bc63e"),
"ProductName": "Product-3",
"ProductPrice": 994
}
{
"_id": ObjectId("5cd7a8d06d78f205348bc63f"),
"ProductName": "Product-4",
"ProductPrice": 1000
}
Decrement Single Value
Decrease Product-4's price by 10 units ?
db.decrementingOperationDemo.update(
{ _id: ObjectId("5cd7a8d06d78f205348bc63f"), ProductPrice: { $gt: 0 } },
{ $inc: { ProductPrice: -10 } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
db.decrementingOperationDemo.find().pretty();
{
"_id": ObjectId("5cd7a8ae6d78f205348bc63c"),
"ProductName": "Product-1",
"ProductPrice": 756
}
{
"_id": ObjectId("5cd7a8b86d78f205348bc63d"),
"ProductName": "Product-2",
"ProductPrice": 890
}
{
"_id": ObjectId("5cd7a8c66d78f205348bc63e"),
"ProductName": "Product-3",
"ProductPrice": 994
}
{
"_id": ObjectId("5cd7a8d06d78f205348bc63f"),
"ProductName": "Product-4",
"ProductPrice": 990
}
Key Points
- The
$incoperator with negative values decrements numeric fields. - Adding
ProductPrice: { $gt: 0 }ensures the price is positive before decrementing. - Only the matched document is modified; other documents remain unchanged.
Conclusion
Use $inc with negative values to decrement single field values in MongoDB. This operator provides precise control over numeric field modifications while maintaining data integrity.
Advertisements
