Articles → MONGODB → $Sum Operator In Mongodb

$Sum Operator 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
        }
      }
    }
  }
])



Output


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




Posted By  -  Karan Gupta
 
Posted On  -  Tuesday, September 26, 2023

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250