cloudant / nodejs-cloudant

Cloudant Node.js client library
Apache License 2.0
255 stars 90 forks source link

How can I get a count of the number of documents in a database? #148

Closed millerbryan closed 8 years ago

millerbryan commented 8 years ago

I see an example using db.list() but it is not clear what is returned.

Is body.rows an object or an integer?

millerbryan commented 8 years ago

After digging deeper into the body object I can use this

var count = 0;

for(var prop in body.rows) {
        if(body.rows.hasOwnProperty(prop))
       ++count;
}

but it isn't elegant.

glynnbird commented 8 years ago

You can use the db.get endpoint to return you meta information about a database as a whole without fetching all the documents. The meta data looks something like this:

{ 
  db_name: 'animaldb',
  doc_count: 12,
  doc_del_count: 7,
  update_seq: 25,
  purge_seq: 0,
  compact_running: false,
  disk_size: 57455,
  data_size: 7210,
  instance_start_time: '1473786786592693',
  disk_format_version: 6,
  committed_update_seq: 25 
}

Here's some code:

var cloudant = require('cloudant')({url:"http://localhost:5984"});
cloudant.db.get("animaldb", function(err, data) {
    console.log(data.doc_count);
});
millerbryan commented 8 years ago

Very nice! Thank you Glenn. Do you mind if I add that to the docs?