How to get a "fieldcount" (like wordcount) on CouchDB/Cloudant?

131 views Asked by At

Trying to get a count of fields, just like the classic word count example. I thought this would be trivial...

enter image description here

but I got this useless result...

{"rows":[
{"key":null,"value":212785214}
]}

How can I get what I wanted... an inventory of all fields used in my documents, with a count of how many times they occur?

1

There are 1 answers

1
Glynn Bird On BEST ANSWER

To get a count of each key in your document, create a "map" function like this:

function (doc) {
  var keys = Object.keys(doc);
  for(var i in keys) {
    emit(keys[i], null);
  }
}

and use the built in _count reducer.

You can then retrieve the grouped answer by accessing the view like so:

/mydb/_design/<designdocname>/_view/<viewname>?group_level=1

which will produce grouped keys and counts like this:

{"rows":[
{"key":"_id","value":4},
{"key":"_rev","value":4},
{"key":"a","value":3},
{"key":"c","value":1}
]}