Question

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.

Was it helpful?

Solution

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);

OTHER TIPS

I guess you could just use this map:

function (doc) {
  emit([doc.author, -doc.views], null);
}

without the reduce. Query with options ?startkey=['john']&limit=2 should result with something like:

{"total_rows":5,"offset":0,"rows":[
{"id":"id1","key":["john",-10],"value":null},
{"id":"id2","key":["john",-3],"value":null}
]}

Note the - sign when emitting doc.view to get biggest view count. You can also use descending=true option, but it will also reverse the order of the author string. This is not natural order for strings and you might need that in the future ;)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top