1

I have schema:

{
 userName: String
 postCount: Number,
 commentCount: Number,
 abuseCount: Number,
}

I need get sum all users counts all fields in result

example

{
 "userName": "John"
 "postCount": 5,
 "commentCount": 1,
 "abuseCount": 4,
}, {
 "userName": "Bob"
 "postCount": 11,
 "commentCount": 41,
 "abuseCount": 3,
}, {
 "userName": "Alex"
 "postCount": 2,
 "commentCount": 15,
 "abuseCount": 6,
}

result must be ~

    {
     "postCount": 18, (sum all postCount field users)
     "commentCount": 57,
     "abuseCount": 10,
    }

How I can do this? Thx!

Jackson
  • 884
  • 2
  • 13
  • 22
  • Possible dupe http://stackoverflow.com/questions/4621300/how-to-sum-the-value-of-a-key-across-all-documents-in-a-mongodb-collection – chridam Feb 21 '17 at 13:00
  • 3
    Try `db.collection.aggregate( [ { $group: { _id: null, postCount: { $sum: "$postCount" }, commentCount: { $sum: "$commentCount" }, abuseCount:{$sum: "$abuseCount" } } } ] )` – s7vr Feb 21 '17 at 13:02
  • oh guy, are you know, if I have 1 boolean field in my schema, can I sum all true values?? – Jackson Feb 21 '17 at 17:08

0 Answers0