cloudant / nodejs-cloudant

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

Count elements in cloudant query #353

Closed eduar2 closed 5 years ago

eduar2 commented 5 years ago

I have a table in cloudant whith something like this:

{  
   "_id":"1",
   "firstName":"A",
   "lastName":"B",
   "children":[  
      {  
         "id":"2",
         "firstName":"A1",
         "lastName":"B1 "
      }
   ],
   "db":"user"
}

The field children can have 0, 1 or n elements.

Is there a way to get using queries, to know what is the max number of elements for this field. Other thing that can be useful is to know the number of children of every document, or record.

emlaver commented 5 years ago

Hi @eduar2, I recommend you look at creating a MapReduce view and use a reduce function (possibly _count or _sum) to give you the count of items within the children array. Stackoverflow is a good source for finding examples that will help you get started e.g. https://stackoverflow.com/questions/48629034/getting-total-count-of-mapped-reduced-records-in-couchdb.

ricellis commented 5 years ago

The built in _stats reduce function includes min and max properties. Emit the length of the children array as the value from your map function e.g.

function(doc) {
  if (doc.children && Array.isArray(doc.children)) {
    emit(doc._id, doc.children.length);
  }
}

Closing as this is not an issue with nodejs-cloudant, it is just a general Cloudant how-to. Please re-open if you need help using nodejs-cloudant to query your view.