gbland777
gbland777

Reputation: 715

React native firebase 'average' query?

I come from a php/mysql background, and json data and firebase queries are still pretty new to me. Now I am working in React Native and I have a collection of data, and one of the keys stores a integer. I want to get the average of all the integers. Where do I even start?

I have used Firebases snapshot.numChildren function before so I am getting a little more familiar in this json world, but any sort of help would be appreciated. Thanks!

Upvotes: 2

Views: 605

Answers (1)

Luke Schlangen
Luke Schlangen

Reputation: 3882

So, you know that you can return all of the data and determine the average. I'm guessing this is for a large set of data where it would be ideal not to return the entire node every time you would like to retrieve and average.

It depends on what this data is and how it's being updated, but I think one option is to simply have a separate node that is updated every time the collection is added to or is changed.

Here is some really rough pseudo code. For example, if your database looks like this:

database
|
+--collection
|   |
|   +--item_one (probably a uid like -k2jduwi5j5j5)
|   |   |
|   |   +--number: 90
|   |
|   +--item_two
|   |   |
|   |   +--number: 70
|
+--collection_metadata
|   |
|   +--average: 80
|   |
|   +--number_of_items: 2

Then when a new item is added, you run a metadata calculation:

var numerator = average * number_of_items + newItem.number;
number_of_items++; <-- this is your new number of items
numerator / number_of_items; <-- this is your new average

Then when an item is updated, you run a metadata calculation:

var numerator = average * number_of_items - changedItem.oldNumber + changedItem.newNumber;
numerator / number_of_items; <-- this is your new average

Now when you want this data, you always have this data on hand.

Upvotes: 4

Related Questions