If each shoe is a document, with a date_in
and date_out
, then your reduce function will +1 if the date_out
is null, and +0 (no change) if date_out
is not null. That will give you the total count of shoes in the warehouse.
To compute the average time, for each shoe, you know the time in the warehouse. So the reduce function simply accumulates the average. Since reduce functions must be commutative and associative, you use a different average algorithm. The easiest way is to reduce to a [sum, count]
array, where sum
is an accumulator of all time for all shoes, and count
is a counter for the number of shoes counted. Then the client simply divides sum / count
to compute the final average.
I think you could combine both of these into one big reduce if you want, perhaps building up a {"shoes in warehouse": 1, "average time in warehouse": [253, 15]}
kind of object.
However, if you can accept two different views for this data, then there is a shortcut for the average. In the map, emit(null, time)
where time
is the time spent in the warehouse. In the reduce, set the entire reduce value to _stats
(see Built-in reduce functions). The view output will be an object with the sum
and count
already computed.