CouchDB count all documents and return a number?

We have a college project in CouchDB and I’m using node, I want to create a view that returns a number of all my documents by email.

I cannot find anything that works and I’m not sure what I’m missing, I tried a lot of different reduce functions and emit methods.

Thanks for any answers.

The documents have 2 fields, name and email

enter image description here

enter image description here

Answer

Do not use the db endpoint because the response field doc_count includes design documents along with other documents that may not have an email field.

A straight forward way to do this is with a view. The code snippet demonstrates the difference between db info doc_count and a view’s total_rows using PouchDB. I’d guess there’s probably more interesting uses for the index.

The design doc is trivial

{
 _id: '_design/my_index',
   views: {
     email: {
       map: function(doc) {
         if (doc.email) emit(doc.email);
       }.toString()
    }
  }
}

And the view query is very efficient and simple.

db.query('my_index/email', {
        include_docs: false,      
        limit: 0
      })

const gel = id => document.getElementById(id);
let db;

function setJsonToText(elId, json) { 
  gel(elId).innerText = JSON.stringify(json, undefined, 3);
}
async function view() {
  // display db info
  setJsonToText('info', await db.info());
  // display total number or rows in the email index
  const result = await db.query('my_index/email', {
    include_docs: false,  
    limit: 0
  });
  setJsonToText('view', result);

}

// canned test documents
function getDocsToInstall() {
  return [{
      email: 'jerry@garcia.com',
    },
    {
      email: 'bob@weir.com',
    },
    {
      email: 'phil@lesh.com'
    },
    {
      email: 'wavy@gravy.com'
    },
    {
      email: 'samson@delilah.com'
    },
    {
      email: 'cosmic@charlie.com'
    },
    // design doc
    {
      _id: '_design/my_index',
      views: {
        email: {
          map: function(doc) {
            if (doc.email) emit(doc.email);
          }.toString()
        }
      }
    }
  ]
}

// init example db instance
async function initDb() {
  db = new PouchDB('test', {
    adapter: 'memory'
  });

  await db.bulkDocs(getDocsToInstall());

};

(async() => {
  await initDb();
  await view();
})();
<script src="https://github.com/pouchdb/pouchdb/releases/download/7.1.1/pouchdb-7.1.1.min.js"></script>
<script src="https://github.com/pouchdb/pouchdb/releases/download/7.1.1/pouchdb.memory.min.js"></script>
<pre>Info</pre>
<pre id='info'></pre>
<div style='margin-top:2em'></div>
<pre>email view</pre>
<pre id='view'>
</pre>