简体   繁体   中英

How to sum arrays from different documents in MongoDB Aggregation?

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.

Example data

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

Expected result for cohorts 2113 and 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?

And yes, I use PyMongo to access the database.

I just discovered this new 3.2 feature: includeArrayIndex .

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.

Reference: https://docs.mongodb.org/manual/reference/operator/aggregation/unwind/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM