Please bear with me, I’m pretty new to the whole CouchDb stuff.
The db looks like:
** item ** count ** user **
A 20 bob
B 30 bob
C 10 bob
D 15 john
I want to write a MapReduce that selects all the items belonging to bob and only return the top 2, sorted. so it should return [{item:"B",count:"30"},{item:"A",count:"20}]
I’m not sure how this can be done? Seems like I have to emit(doc.item, doc.count), but how do I know if the user owns the doc? How do I run another MapReduce to select the top elements?
One solution would be to write your view to use a complex key, such as:
If you add
descending=trueto your query string, that would give you a view result like:It’s sorted already by user, then count. (with the item type as the value)
Then you can use a
_listfunction to do the rest. The code below basically loops through the view, and returns the top 2 results for each user. If you specifyuser=bobin the query string, you’ll only get the results forbob.