What is the CouchDB equivalent of the SQL COUNT(*) aggregate function?

Brad Gessler picture Brad Gessler · Oct 19, 2009 · Viewed 18.6k times · Source

Yep, I'm a SQL jockey (sorta) coming into the CouchDb Map/Reduce world. I thought I had figured out how the equivalent of the COUNT(*) SQL aggregator function for CouchDB datasets with the following:

Map:

function(doc) {
  emit(doc.name, doc);
}

Reduce:

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

Which I thought worked, returning something like:

"super fun C"   2
"super fun D"   2
"super fun E"   2
"super fun F"   18

... but not really. When I add a record, this count varies wildly. Sometimes the count actually decreases, which was very surprising. Am I doing something wrong? Maybe I don't fully understand the concept of eventual consistency?

Answer

David Coallier picture David Coallier · Mar 30, 2010

In your reduce just put:

_count

You can also get a sum using:

_sum

so basically reduce: "_sum" or reduce: "_count" and make sure the value your map emits is a valid integer (numeric value)

See "Built in reduce functions".