incubator-couchdb-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Gabor Ratky <>
Subject Re: how to sum values of a view in a date range?
Date Thu, 09 Jun 2011 16:27:40 GMT
Update your design document as follows:

 "_id": "_design/power",
 "_rev": "1-7788287ab51c480c725498eba4f79ddb",
 "language": "javascript",
 "views": {
 "watt": {
 "map": "function(doc) {\n emit(doc._id, doc.volt * doc.ampere);\n}"
 "reduce": "_stats"

You can then query your view with ?group=true&group_level=2 to get statistics for each
month. The built-in reduce function _stats contains both sum and count, so you can get to
the average as well. You can also use the following reduce function to calculate the average

avg_function = function(keys, values, rereduce) {
var avg, length;
if (!rereduce) {
length = values.length;
return [sum(values) / length, length];
} else {
length = sum( {
return v[1];
avg = sum( {
return v[0] * (v[1] / length);
return [avg, length];

(Sorry if the code could be more readable, it was produced by CoffeeScript, not me)

The reduced view will contain a pair of numbers in an array, where the first number is the
average and the second number is the count. The other comment I have is that you shouldn't
have the date in your _id, but rather in a date field, so you documents would be better off

 "_id": "<some random id>",
 "_rev": "1-...",
 "date": [2011, 6, 7, 10, 55]
 "volt": 107,
 "ampere": 23.5


On Thursday, June 9, 2011 at 6:06 PM, Fabio Di Bernardini wrote:

> Il 09/06/2011 17:18, Fabio Di Bernardini ha scritto:
> > If I have a map function emitting a timestamp as key ad a number as 
> > document, how to get sum of values selecting a date range?
> More datails here:

  • Unnamed multipart/alternative (inline, None, 0 bytes)
View raw message