如何在MongoDB聚合中汇总来自不同文档的数组? [英] How to sum arrays from different documents in MongoDB Aggregation?

查看:132
本文介绍了如何在MongoDB聚合中汇总来自不同文档的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文档集合,每个文档包含一系列不同长度的收入。

我想从与查询匹配的值中获取一个收入数组。

I have a collection of documents, each containing an array of revenues of different lengths.
I want to get a single array of revenue from the values that match the query.

示例数据

...
{"cohort": "2112", "revenue": [1, 1, 0, 0, 5], ...},
{"cohort": "2113", "revenue": [0, 0, 2, 0], ...},
{"cohort": "2114", "revenue": [0, 1, 3], ...}
...

同类群组2113和2114的预期结果

[0, 1, 5] or [0, 1, 5, 0]

这两个结果对我而言是相等的,因为我知道最短数组的长度。

有什么方法可以执行该操作

还是可以建议一个更好的解决方案?

The two results are equal for my purpose, since I know the length of the shortest array.
Is there any way to perform the operation with MongoDB Aggregate pipeline?
Or can you suggest a better solution?

是的,我使用PyMongo访问数据库。

And yes, I use PyMongo to access the database.

推荐答案

我刚刚发现了这个新的3.2功能: includeArrayIndex

I just discovered this new 3.2 feature: includeArrayIndex.

因此,您可以使用此选项放宽字段收入,然后使用您的 sum includeArrayIndex 字段作为id和d然后 sort push 获得一个新数组。

So you can unwind the field revenue with this option and then sum using your includeArrayIndex field as id and then sort and push to get a new array.

参考: https://docs.mongodb.org/manual/reference/运算符/集合/展开/

这篇关于如何在MongoDB聚合中汇总来自不同文档的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆