Sum results of multiple grouped documents
<p>I have setup a schema where I associate two different entities: Users and Brands. This association is stored in the document UserBrand. A user may have multiple brands, and in each UserBrand document, the information there contained is different.</p>

<p>Here is an example of three documents:</p>

<pre><code>{
    type: "UserBrand",
    userId: "x",
    brandId: 1,
    value: 100
}

{
    type: "UserBrand",
    userId: "x",
    brandId: 2,
    value: 50
}

{
    type: "UserBrand",
    userId: "y",
    brandId: 1,
    value: 150
}
</code></pre>

<p>As you see, user 'x' follows multiple brands. How can I get the sum of the values grouped by user, while fetching the user information as well?</p>

<p>So far I am able to join both document types (User and UserBrand) through this query:</p>

<pre><code>SELECT ub.*, u.name FROM bucket as ub JOIN bucket as u ON KEYS "User_" || ub.userId WHERE ub.type="UserBrand" AND u.type="User" AND (ub.brand=1 OR ub.brand=2)
</code></pre>

<p>but I cannot seem to group the records and sum the values for a single user. Is it possible to do so on a single query?</p>

<p>If possible, the end result should be something like:</p>

<pre><code>{
    type: "UserBrand",
    name: "name1',
    userId: "x",
    brandId: 1,
    value: 150
}

{
    type: "UserBrand",
    name: "name2',
    userId: "y",
    brandId: 1,
    value: 150
}
</code></pre>