How to count the documents returned by a Mango query
Asked Answered
P

2

11

I have a mango query:

{
  "selector": {
    "age":{
        "$eq": 22
    }
  }
}

I want to know the number of documents that satisfy this criteria.

I know we can use map reduce functions to achieve this, but is there any way to do this by using mango query like using some key like "count" in the query itself as we do for "sort", and "fields".

I am firing mango query through rest client and I want the number of documents as the response of the query.

Protoxide answered 27/4, 2017 at 12:24 Comment(2)
Did you find a solution?Headword
No, I was looking for something similar to SQL "Select count(column_name)" that directly gives the count of number of documents that match the condition, instead of doing docs.length to get the countProtoxide
E
1

CouchDB returns an object. In this object you'll find an array "docs". Just get the length of this array and you'll have the number of returned documents.

Eveliaevelin answered 22/5, 2017 at 21:0 Comment(2)
So if i need to do pagination (limit) i have to execute 2 quires right ? one is to get count one is to get results. Am i right ?Woollen
@Yuvaraj I come to the same conclusion like you. However instead of two queries you could still run just one query for all and then implement the limit and skip on your own. However answer of g0xr shows me: couchdb seems not to be made for this. The official couch db gui "Fauxton" solves it in a simple way: If the current result page has less then the limit, the "next" button get's disabled. If you click the "next" button too fast, the gui is not accuretely showing the current page anymore.Samovar
B
0

It is not really possible to retrieve the full number of documents by using the find function. By default _find is limited to 25 documents to be returned (http://docs.couchdb.org/en/2.0.0/api/database/find.html).

limit (number) – Maximum number of results returned. Default is 25. Optional

By increasing this number, the response time is increasing. Having e.g. 15.000 entries in your couch database and limiting the query to 999999 would result in a long waiting time.

Back to your question: after receiving your result set, simply run something like array.length to count your results.

Blume answered 6/6, 2017 at 9:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.