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
Perform Group in MongoDB and sum the price record of documents
To sum price records across all documents in MongoDB, use the $group stage in an aggregation pipeline with the $sum operator. Set _id: null to group all documents together.
Syntax
db.collection.aggregate([
{
$group: {
_id: null,
totalFieldName: { $sum: "$fieldName" }
}
}
]);
Sample Data
db.demo527.insertMany([
{ "Price": 45.5 },
{ "Price": 55.5 },
{ "Price": 100.4 },
{ "Price": 200.6 }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e8aff2fef4dcbee04fbbbdc"),
ObjectId("5e8aff34ef4dcbee04fbbbdd"),
ObjectId("5e8aff39ef4dcbee04fbbbde"),
ObjectId("5e8aff40ef4dcbee04fbbbdf")
]
}
Display Sample Data
db.demo527.find();
{ "_id": ObjectId("5e8aff2fef4dcbee04fbbbdc"), "Price": 45.5 }
{ "_id": ObjectId("5e8aff34ef4dcbee04fbbbdd"), "Price": 55.5 }
{ "_id": ObjectId("5e8aff39ef4dcbee04fbbbde"), "Price": 100.4 }
{ "_id": ObjectId("5e8aff40ef4dcbee04fbbbdf"), "Price": 200.6 }
Example: Sum All Price Records
db.demo527.aggregate([
{
$group: {
_id: null,
totalPrice: { $sum: "$Price" }
}
}
]);
{ "_id": null, "totalPrice": 402 }
Key Points
-
_id: nullgroups all documents into a single result. -
$sum: "$Price"adds up values from the Price field across all documents. - The result contains the calculated total in the specified field name.
Conclusion
Use $group with $sum in MongoDB aggregation to calculate totals across document collections. Setting _id: null ensures all documents are grouped together for a single sum result.
Advertisements
