Reputation: 2835
For a table with the following results (not necessarily records with ids):
[{time: 4, votes: 10}, {time: 6, votes: 3} ... ]
How can I get the following result (or similar):
{average_time: 5, total_votes: 13}
by running only ONE query and not two?
Upvotes: 1
Views: 344
Reputation: 197
try this :)
r.object(
'average_time',
r.table('data')('time').avg(),
'total_votes',
r.table('data')('votes').sum()
)
Upvotes: 1
Reputation: 4353
You can use reduce to perform multiple aggregations. This should work
r.table('data').map(function(doc) {
return {
total_votes: doc("votes"),
total_time: doc("times"),
count: 1
}
}).reduce(function(left, right) {
return {
total_votes: left("total_votes").add(right("total_votes")),
total_time: left("total_time").add(right("total_time")),
count: left("count").add(right("count"))
}
}).map(function(result) {
return {
total_votes: result("total_votes"),
average_time: result("total_time").div(result("count"))
}
})
Upvotes: 1