W3cubDocs

/RethinkDB Java

ReQL command: avg

Command syntax

sequence.avg([field | function]) → number
r.avg(sequence, [field | function]) → number

Description

Averages all the elements of a sequence. If called with a field name, averages all the values of that field in the sequence, skipping elements of the sequence that lack that field. If called with a function, calls that function on every element of the sequence and averages the results, skipping elements of the sequence where that function returns null or a non-existence error.

Produces a non-existence error when called on an empty sequence. You can handle this case with default.

Example: What’s the average of 3, 5, and 7?

r.expr(r.array(3, 5, 7)).avg().run(conn);

Example: What’s the average number of points scored in a game?

r.table("games").avg("points").run(conn);

Example: What’s the average number of points scored in a game, counting bonus points?

r.table("games").avg(
    game -> game.g("points").add(game.g("bonus_points"))
).run(conn);

Example: What’s the average number of points scored in a game? (But return null instead of raising an error if there are no games where points have been scored.)

r.table("games").avg("points").default_(null).run(conn);

Related commands

Get more help

Couldn't find what you were looking for?

© RethinkDB contributors
Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License.
https://rethinkdb.com/api/java/avg/