I have the following documents
{
"_id": "id",
"_rev": "123456",
"author": "john",
"views": "3",
},
{
"_id": "id",
"_rev": "123456",
"author": "jake",
"views": "5",
},
{
"_id": "id",
"_rev": "123456",
"author": "jake",
"views": "6",
},
{
"_id": "id",
"_rev": "123456",
"author": "john",
"views": "1",
},
{
"_id": "id",
"_rev": "123456",
"author": "jake",
"views": "7",
},
{
"_id": "id",
"_rev": "123456",
"author": "john",
"views": "10",
}
Lets suppose that these are comments and I would like to get the 2 most viewed comments by user.
How can I do that in CouchDB?
In any other sql database I could perform 2 queries with limit 2
and then merge the results.
If you have an array with that data in JavaScript you can simply use the sort method:
var a = [{...}, {...}, {...}];
a.sort(function(a, b) {
return b.views - a.views;
});
console.log(a[0]) //{ "_id": "id", "_rev": "123456", "author": "john", "views": "10" }
console.log(a[1]) //{ "_id": "id", "_rev": "123456", "author": "jake", "views": "7" }
If you want to only have the to most viewed records you can use the slice method
var a = [...];
a.sort(...);
a = a.slice(0, 2);