Reputation: 3027
I have multiple CouchDB documents representing a timestamp with a property userId and tag (a user can have n timestamps and assign each one a tag). I want to query CouchDB by a specific userId and get a sorted list of tags the user has used (sorted by occurrence).
How would the view look like?
If I want to get a list of all tags sorted by occurrence (no matter from which user) or if I assume that there are only documents with the same userId, I would make it like so:
Map:
function(doc) {
if(doc.tag) emit(doc.tag, 1);
}
Reduce:
function(keys, values) {
return sum(values);
}
But how do I group the result so that I can filter the query by a specific userId?
Upvotes: 7
Views: 6383
Reputation: 3027
Answering my own question.
Seems like CouchDB supports arrays as keys. With that in mind it's pretty simple:
Map:
function(doc) {
if(doc.tag) emit([doc.userId, doc.tag], 1);
}
Reduce:
function(keys, values) {
return sum(values);
}
The result is then sorted by userId & tag.
Upvotes: 10