MongoDB聚合以将动态键分组

编程入门 行业动态 更新时间:2024-10-25 02:29:45
本文介绍了MongoDB聚合以将动态键分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在像这样的数据结构中对可变数量的条形行的值的计数进行聚合:

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

推荐答案

您可以使用MongoDB的聚合框架:

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聚合以将动态键分组

本文发布于:2023-11-22 19:38:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618750.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:动态   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!