gbegley
gbegley

Reputation: 2679

In a mongodb group/map command determine the group's percentage of a total

In a mongodb group operation, is their a way to determine totals during finalization, for eaxample to determine the groups percentage of the collection's total.

For example, after the grouping operation is completed, I know that group A has an aggregate qty of 50. Is their a way to get the group's qty values as a percentage of the total?

Or do I have to save results to a collection, determine the totals, then go back and update each document with a calculated percentage of the total for the group?

Upvotes: 1

Views: 1771

Answers (1)

dcrosta
dcrosta

Reputation: 26258

MongoDB map-reduce supports a scope field, which sets Javascript globals available to map, reduce, and finalize functions. You could add a field to scope and track the total during either map or reduce phases, whichever makes most sense for your use case; you can then access this during finalize to compute the percentage for each output group.

Upvotes: 4

Related Questions