The official documentation has moved to http://docs.couchdb.org — The transition is not 100% complete, but http://docs.couchdb.org should be seen as having the latest info. In some cases, the wiki still has some more or older info on certain topics inside CouchDB. |

You need to be added to the ContributorsGroup to edit the wiki. But don't worry! Just email any Mailing List or grab us on IRC and let us know your user name. |

# Built-In Reduce Functions

See also the official documentation for this topic.

CouchDB has three built-in reduce functions. These are implemented in Erlang and run right inside CouchDB, so they are much faster than the equivalent JavaScript functions.

## Usage

To use built-in reduce functions, you simply need to replace your reduce function with the string `_count`, `_sum` or `_stats` (without any preceding or tailing whitespace).

Here is an example design document using built-in reduce functions:

{ "_id":"_design/company", "_rev":"12345", "language": "javascript", "views": { "all_customers": { "map": "function(doc) { if (doc.type == 'customer') emit(doc.id, 1) }", "reduce" : "_count" }, "total_purchases_by_customer": { "map": "function(doc) { if (doc.type == 'purchase') emit(doc.customer_id, doc.amount) }", "reduce": "_sum" } } }

## Available Built-In Functions

### _sum

`_sum` just adds up the emitted values, which must be numbers.

The JavaScript equivalent is:

function(keys, values, rereduce) { return sum(values); }

### _count

`_count` counts the number of emitted values. (It's like `_sum` for `emit(foo, 1)`.) It ignores the contents of the values, so they can by any type.

The JavaScript equivalent is:

function(keys, values, rereduce) { if (rereduce) { return sum(values); } else { return values.length; } }

### _stats

`_stats` calculates some numerical statistics on your emitted values, which must be numbers.

The reduce output is an object that looks like this:

{"sum":2,"count":2,"min":1,"max":1,"sumsqr":2}

`"sum"` and `"count"` are equivalent to the `_sum` and `_count` reductions. `"min"` and `"max"` are the minimum and maximum emitted values. `"sumsqr"` is the sum of the squares of the emitted values (useful for statistical calculations like standard deviation).