Articles → MONGODB → $Sum and $Group Operators In MongoDB

$Sum and $Group Operators In MongoDB






Purpose





Sales Table




db.sales.insertMany([
{ "_id": 1, "product": "A", "quantity": 5, "price": 10 },
{ "_id": 2, "product": "B", "quantity": 3, "price": 15 },
{ "_id": 3, "product": "A", "quantity": 2, "price": 12 },
{ "_id": 4, "product": "C", "quantity": 6, "price": 8 }
])



Sum Operator




db.sales.aggregate([
  {
    $group: {
      _id: "$product",    // Group by the "product" field
      totalSales: {
        $sum: {            // Use $sum to calculate the total sales within each group
          $multiply: ["$quantity", "$price"] // Multiply quantity by price for each document
        }
      }
    }
  }
])



Group Stage







Output


Picture showing the output of $sum operator in MongoDB
Click to Enlarge




Posted By  -  Karan Gupta
 
Posted On  -  Tuesday, September 26, 2023
 
Updated On  -  Tuesday, June 4, 2024

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250