MongoDB聚合以将动态键分组 [英] MongoDB aggregation to group dynamic keys
问题描述
我正在像这样的数据结构中对可变数量的条形行的值的计数进行聚合:
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:
所需的输出:
bar0: 16
bar1: 24
bar2: 2
bar3: 45
bar4: 48
bar5: 21
bar6: 16
bar7: 8
bar8: 8
推荐答案
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"
}
}
])
测试: mongoplayground
注意::尽量不要使用动态键名-这会导致读取时出现许多问题,在上述查询中,在 $ group
之后的阶段也是可选的,它们在那里为了使输出看起来像所需的格式,最好进行测试,直到 $ group
阶段&检查是否可以满足您的需求.
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.
这篇关于MongoDB聚合以将动态键分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!