Having problem to sum up values against some key values

{ “_id” : ObjectId(“617f68ae84b0a3bf2c879c74”), “key” : “emily”, “profit” : { “time” : 1633132800, “percent” : 2 } }
{ “_id” : ObjectId(“61854585f14b328ab559f0dc”), “key” : “emily”, “profit” : { “time” : 1634601600, “percent” : 4 } }
{ “_id” : ObjectId(“61854586f14b328ab559f0dd”), “key” : “bilz”, “profit” : { “time” : 1635465600, “percent” : 3 } }
{ “_id” : ObjectId(“61854586f14b328ab559f0de”), “key” : “bilz”, “profit” : { “time” : 1635724800, “percent” : 5 } }
{ “_id” : ObjectId(“61854587f14b328ab559f0df”), “key” : “faisal”, “profit” : { “time” : 1635379200, “percent” : 1 } }
{ “_id” : ObjectId(“61854593f14b328ab559f0e0”), “key” : “faisal”, “profit” : { “time” : 1635033600, “percent” : 3 } }
{ “_id” : ObjectId(“61854593f14b328ab559f0e1”), “key” : “hamza”, “profit” : { “time” : 1633564800, “percent” : 4 } }
{ “_id” : ObjectId(“61854594f14b328ab559f0e2”), “key” : “hamza”, “profit” : { “time” : 1635724800, “percent” : 2 } }
{ “_id” : ObjectId(“6185459bf14b328ab559f0e3”), “key” : “saif”, “profit” : { “time” : 1635292800, “percent” : 17 } }
{ “_id” : ObjectId(“6185459cf14b328ab559f0e4”), “key” : “saif”, “profit” : { “time” : 1633910400, “percent” : 6 } }
{ “_id” : ObjectId(“6185459df14b328ab559f0e5”), “key” : “umer”, “profit” : { “time” : 1635206400, “percent” : 8 } }
{ “_id” : ObjectId(“6185459df14b328ab559f0e6”), “key” : “umer”, “profit” : { “time” : 1635724800, “percent” : 4 } }
{ “_id” : ObjectId(“6185459ef14b328ab559f0e7”), “key” : “zeeshan”, “profit” : { “time” : 1635724800, “percent” : 9 } }
{ “_id” : ObjectId(“61854a041dbfe67422fdb4e5”), “key” : “zeeshan”, “profit” : { “time” : 1608422400, “percent” : 2 } }

i have this data in database. i want to group sum percent values which have same value in key
i.e key value have “emily” . so i want to add all emily percent values and so on like this
emily : 2 + 4 = 6
bilz : 3 + 5 = 8
faisal : 1 + 3 = 4
and so on

Please share what you have tried and give some more information about the problem you are having.

I tried many queries and finally I’m able to solve this. here is the query

db.collection.aggregate(
   [
     {
       '$group':
          {
            "_id": "$namespace",
            "sum": { '$sum': "$profit.percent" }
          }
     }
   ]
)
1 Like

But from the sample data you posted you will want

"_id" : "$key" ,

rather than

"_id" : "$namespace" ,

oops! my bad…
yes “_id” : “$key” is correct

db.collection.aggregate(
   [
     {
       '$group':
          {
            "_id": "$key",
            "sum": { '$sum': "$profit.percent" }
          }
     }
   ]
)
1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.