jamseernj
jamseernj

Reputation: 1052

MongoDB SUM Of 2 Columns

I have a following documents in my collection:

{ "_id" : ObjectId("5785e5649b732ab238cfc519"), "name" : "Apple", "category" : "Fruit", "price" : 100, "discount" : 5 }
{ "_id" : ObjectId("5785e5709b732ab238cfc51a"), "name" : "Orange", "category" : "Fruit", "price" : 90, "discount" : 5 }
{ "_id" : ObjectId("5785e5819b732ab238cfc51b"), "name" : "PineApple", "category" : "Fruit", "price" : 60, "discount" : 2 }
{ "_id" : ObjectId("5785e5969b732ab238cfc51c"), "name" : "Potatto", "category" : "Vegetable", "price" : 10, "discount" : 1 }
{ "_id" : ObjectId("5785e5c39b732ab238cfc51d"), "name" : "Cabbage", "category" : "Vegetable", "price" : 5, "discount" : 1 }

And Expected Result

{ "_id" : { "category" : "Vegetable" }, "total" : 15 }

And I am using mongoDB query to find the Sum of total with vegetable category as follows

db.stall.aggregate([{$group: {_id: {category: "Vegetable" }, total: {$sum: "$price"}}}]);

But I am getting the following result

{ "_id" : { "category" : "Vegetable" }, "total" : 265 }

How should I find the sum of total and discount columns with vegetable category.

Upvotes: 0

Views: 227

Answers (1)

Tan Kim Loong
Tan Kim Loong

Reputation: 1035

I'm not sure if I'm getting your question right but this will filter the sume of Price and sum of Discount for Vegetable category.

db.stall.aggregate([
   {
      {$match : {category : "Vegetable"}},
      {$group : {_id: "$category", sumOfTotal : {$sum : "$price"}, sumOfDiscount : {$sum : "$discount"}}}
   }
])

Upvotes: 3

Related Questions