Differences between revisions 6 and 7
Revision 6 as of 2012-08-03 05:32:22
Size: 2059
Editor: 173-228-7-198
Comment: Grammatical cleanup
Revision 7 as of 2013-06-05 21:55:29
Size: 2195
Editor: 71
Comment: official docs link
Deletions are marked like this. Additions are marked like this.
Line 4: Line 4:

See also the [[http://docs.couchdb.org/en/latest/ddocs.html#reduce-and-rereduce-functions|official documentation]] for this topic.

We have a new wiki. The migration is not 100% complete. You can help out by moving pages across. This wiki will exist for as long as there are pages left.

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.


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:

  "language": "javascript",
    "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 just adds up the emitted values, which must be numbers.

The JavaScript equivalent is:

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


_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 calculates some numerical statistics on your emitted values, which must be numbers.

The reduce output is an object that looks like this:


"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).

Built-In_Reduce_Functions (last edited 2013-06-05 21:55:29 by 71)