Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select top/latest 10 in couchdb?

How would I execute a query equivalent to "select top 10" in couch db?

For example I have a "schema" like so:

title   body   modified

and I want to select the last 10 modified documents.

As an added bonus if anyone can come up with a way to do the same only per category. So for:

title   category   body   modified

return a list of latest 10 documents in each category.

I am just wondering if such a query is possible in couchdb.

like image 299
Andriy Drozdyuk Avatar asked Apr 06 '10 03:04

Andriy Drozdyuk


1 Answers

To get the first 10 documents from your db you can use the limit query option. E.g. calling

http://localhost:5984/yourdb/_design/design_doc/_view/view_name?limit=10

You get the first 10 documents.

View rows are sorted by the key; adding descending=true in the querystring will reverse their order. You can also emit only the documents you are interested using again the querystring to select the keys you are interested. So in your view you write your map function like:

function(doc) {
    emit([doc.category, doc.modified], doc);
}

And you query it like this:

http://localhost:5984/yourdb/_design/design_doc/_view/view_name?startkey=["youcategory"]&endkey=["youcategory", date_in_the_future]&limit=10&descending=true
like image 102
filippo Avatar answered Sep 18 '22 20:09

filippo