MongoDB aggregation to group dynamic keys

不打扰是莪最后的温柔 提交于 2021-01-27 20:06:36

问题


I'm working on an aggregation of counts of the value of a variable number of bar rows like in this data structure :

> db.data.find()
{ "_id" : "foo1", "1" : { "bar" : 6 }, "0" : { "bar" : 11 }, "3" : { "bar" : 8 }, "2" : { "bar" : 0 }, "5" : { "bar" : 8 }, "4" : { "bar" : 19 }, "6" : { "bar" : 8 } }
{ "_id" : "foo2", "1" : { "bar" : 18 }, "0" : { "bar" : 3 }, "3" : { "bar" : 19 }, "2" : { "bar" : 0 }, "5" : { "bar" : 13 }, "4" : { "bar" : 17 }, "7" : { "bar" : 8 }, "6" : { "bar" : 8 }, "8" : { "bar" : 8 } }
{ "_id" : "foo3", "1" : { "bar" : 0 }, "0" : { "bar" : 2 }, "3" : { "bar" : 18 }, "2" : { "bar" : 2 }, "4" : { "bar" : 12 } }

I'm able to do this individually, but is it possible to do this across the whole data set? Output format isn't really import to me, but here's an idea:

Desired Output :

bar0: 16
bar1: 24
bar2: 2
bar3: 45
bar4: 48
bar5: 21
bar6: 16
bar7: 8
bar8: 8

回答1:


You can do that using MongoDB's aggregation framework :

db.collection.aggregate([
    /** Remove not needed fields, which will lessen size of doc */
    { $project: { _id: 0 } },
    /** As you've dynamic field names - convert each field in doc into {k:...,v:...} & entire doc is pushed into array field `data` */
    {
      $project: { data: {  $objectToArray: "$$ROOT" } }
    },
    {
      $unwind: "$data"
    },
    /** group to bring same 'k' values together & sum-up bar value */
    {
      $group: { _id: "$data.k", bar: { $sum: "$data.v.bar" } }
    },
    /** Can be Optional, Project needed fields `data` will be an object */
    {
      $project: {
        _id: 0,
        data: { $arrayToObject: [ [ { "k": { $concat: [ "bar", "$_id" ] }, "v": "$bar" } ] ] } } 
    },
    /** Make `data` field as new root for doc */
    {
      $replaceRoot: {
        newRoot: "$data"
      }
    }
  ])

Test : mongoplayground

Note : Try not to have dynamic key names - Which will lead to many issues on reads, Also stages after $group are optional in above query they're there to get the output look like in desired format, better to test till $group stage & check if it's ok for your need.



来源:https://stackoverflow.com/questions/61462351/mongodb-aggregation-to-group-dynamic-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!