MongoDB aggregate fields without knowing all the fields before hand

前端 未结 1 1161
日久生厌
日久生厌 2021-01-18 11:54

How can I compute the aggregate of the following metrics without knowing all the metrics before hand? Can I accomplish this using the aggregate framework or MapReduce?

相关标签:
1条回答
  • 2021-01-18 12:07

    You can try below aggregation.

    Convert the object into array of key value pairs followed by $unwind+$group to group by each key and accumulate the count. Final step to go back to named key value object.

    db.colname.aggregate([
      {"$addFields":{"metrics":{"$objectToArray":"$metrics"}}},
      {"$unwind":"$metrics"},
      {"$group":{
        "_id":{"id":"$player_id","key":"$metrics.k"},
        "count":{"$sum":"$metrics.v"}
      }},
      {"$group":{
        "_id":"$_id.id",
        "metrics":{"$mergeObjects":{"$arrayToObject":[[["$_id.key","$count"]]]}}
      }}
    ])
    
    0 讨论(0)
提交回复
热议问题