1

I'm new to CouchDB and I'm looking for the best way to perform the following count:

I've got documents that look like this:

{
field_1: "some_string",
field_2: "some_other_string"
}

I want to count all documents that have a certain value in field_2, so that I know what´s the limit I should set when finding all documents with that field value via POST /{db}/_find using a selector.

I've read some things about Design Documents and Views and Query Protocol, but I can't understand what's the proper way of achieving this. Do I even need to count first the number of documents? Or is there a way to quickly know this when performing the lookup?

Sasha Fonseca
  • 2,257
  • 23
  • 41
  • Possible duplicate of [What is the CouchDB equivalent of the SQL COUNT(\*) aggregate function?](https://stackoverflow.com/questions/1586585/what-is-the-couchdb-equivalent-of-the-sql-count-aggregate-function) – Jonathan Hall Mar 18 '18 at 18:09

1 Answers1

0

... when finding all documents with that field value ...

I assume your purpose is to find all docs with a specific field having a certain value.

I don't know much about CouchDB mango queries with /<db>/_find or /<db>/_index, but I think you can find all docs with a specific field value by just doing HTTP requests.


Assume you have documents like below, and you want to find all docs with title field equal to Jacob string:

{
  "_id": "doc5",
  "_rev": "1-27f5da5ca3157d4bca8b485d411e86c5",
  "unicodeString": "יעקב",
  "title": "Jacob"
}

You can implement a view map function like below. This view, sorts all docs inside the database according to the title field in a B-tree data structure:

function (doc) {
  if(doc.title){
    emit(doc.title, [doc.unicodeString])
  }
}

Lets assume the name of the above view is by_title and the name of database is sample, then we can do a HTTP request like below to get all the docs with the title field equal to, for example, Jacob string:

$ curl -k -X GET https://joe:joe@192.168.1.106:6984/sample/_design/by_title/_view/by_title?key=\"Jacob\"
{"total_rows":15,"offset":8,"rows":[
{"id":"doc5","key":"Jacob","value":["יעקב"]},
{"id":"doc6","key":"Jacob","value":["ישראל"]}
]}

As you see the above HTTP GET request with curl returns all the docs with the title field equal to Jacob string. I'm using https along with 6984 port, since I'm using CouchDB with SLL and self-signed certificate, but you can use it with http and port 5984.

Also in the above curl command i'm using my key with escaped double-quotes like this: ?key=\"Jacob\". The reason for this is that my Linux shell command line eats the double-quotes before passing them to curl, therefore I have to escape them to make it work.

Megidd
  • 7,089
  • 6
  • 65
  • 142