0

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.

1 Answer 1

0

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/

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I missed that includeArrayIndex option

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.