Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>One solution would be to write your view to use a complex key, such as:</p> <pre><code>function (doc) { emit([doc.user, doc.count], doc.item); } </code></pre> <p>If you add <code>descending=true</code> to your query string, that would give you a view result like:</p> <pre><code>{"total_rows":4,"offset":0,"rows":[ {"id":"53f359b7cd360da296dd9aab3d0029bd","key":["john",15],"value":"D"}, {"id":"53f359b7cd360da296dd9aab3d001a0e","key":["bob",30],"value":"B"}, {"id":"53f359b7cd360da296dd9aab3d000fec","key":["bob",20],"value":"A"}, {"id":"53f359b7cd360da296dd9aab3d002668","key":["bob",10],"value":"C"} ]} </code></pre> <p>It's sorted already by user, then count. (with the item type as the value)</p> <p>Then you can use a <a href="http://guide.couchdb.org/editions/1/en/transforming.html" rel="nofollow"><code>_list</code> function</a> to do the rest. The code below basically loops through the view, and returns the top 2 results for each user. If you specify <code>user=bob</code> in the query string, you'll only get the results for <code>bob</code>.</p> <pre><code>function (head, req) { // specify that we're sending JSON as our response provides('json', function () { var results = [], result, user, count, row; while (row = getRow()) { // if the user doesn't match the last iteration, reset our counter if (user != row.key[0]) { user = row.key[0]; count = 0; } // we only need the top 2 if (count++ &gt;= 2) { continue; } // start building a result object result = { item: row.value, count: row.key[1] }; // if we provide user=? if (req.query.user) { // check to see if it matches the current user if (req.query.user === user) { // if so, add it to the results results.push(result); } // by default, we'll return the top 2 for every user } else { // add the user key to the result object result.user = row.key[0]; // and add it to the result set results.push(result); } } // send outside the loop, since it needs to be sent as valid JSON send(JSON.stringify(results)); }); } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload