I accomplished this using a list function on the view. Here's the overview:
- The View handles selecting the date range (key by date and use
.../myview?startkey=20150101&endkey=20150130
- The List has some Javascript which groups by type. (As a bonus, you can also sort).
My List function looks like this (based on this Q&A about grouping a javascript array by type):
function (head, req){
var row;
var rows = [];
while(row = getRow()){
rows.push({
"type": row.value.type,
"value1": row.value.value1,
"value2": row.value.value2
});
};
var result = rows.reduce(function(res, obj) {
if (!(obj.type in res)){
res.__array.push(res[obj.type] = obj);
} else {
res[obj.symbol].value1 += obj.value1;
res[obj.symbol].value2 += obj.value2;
}
return res;
},
{__array:[]}).__array;
send(toJSON(result));
}
The prior View should emit
the date as the key, and a javascript object as the value. In this example, a row of the view should look like: "key":20150101, "value":{"type":"apple", "value1":28, "value2":0}
. If you are new to Couch, here is how you write your map
function (and don't use a reduce however tempted you may be to _sum
):
function(doc){
if (doc.type === "mydoctype"){
// build array for the day
var items = [];
doc.items.forEach(function(item){
items.push({
'type': item.type,
'value1': +item.value1,
'value2': +item.value2
});
});
items.forEach(function(item){
// convert text date "yyyy-mm-dd"
var x = doc.date.split('-');
// to numerical date YYYYMMDD
newformatdate = +(x[0]+x[1]+x[2]);
emit(newformatdate, item);
});
}
}
Lastly, your query would look like this:
http://localhost:5984/dbname/_design/ddocname/_list/mylistname/myviewname?startkey=20150501&endkey=20150510
I am somewhat new to both Javascript and Couch, so feel free to take a whack at this code.