user10482273
user10482273

Reputation:

How to sum key value of all documents

I am just new to Mongo DB an facing problem in summation of the key value of all documents...

Here I am providing the sample data of Mongo DB-

{ _id: 1, cust_id: "abc1", ord_date: ISODate("2012-11-02T17:04:11.102Z"), status: "A", amount: 50 }    

{ _id: 2, cust_id: "xyz1", ord_date: ISODate("2013-10-01T17:04:11.102Z"), status: "A", amount: 100 }    

{ _id: 3, cust_id: "xyz1", ord_date: ISODate("2013-10-12T17:04:11.102Z"), status: "D", amount: 25 }    

{ _id: 4, cust_id: "xyz1", ord_date: ISODate("2013-10-11T17:04:11.102Z"), status: "D", amount: 125 }    

{ _id: 5, cust_id: "abc1", ord_date: ISODate("2013-11-12T17:04:11.102Z"), status: "A", amount: 25 }

All i want is to get the total value of key "amount", like for example- 50+100+25+125+25

Upvotes: 0

Views: 44

Answers (1)

guneraykut
guneraykut

Reputation: 181

You can query like this:

db.yourCollection.aggregate({ $group: { _id : null, sum : { $sum: "$amount" } } });

More details about aggregation can be found at here, and more details about sum can be found here

Upvotes: 1

Related Questions