Q:

Firebase cloud function to count and update collections

I have three collections in my Firebase project, one contains locations that users have checked in from, and the other two are intended to hold leaderboards with the cities and suburbs with the most check ins.
However, as a bit of a newbie to NOSQL databases, I'm not quite sure how to do the queries I need to get and set the data I want.
Currently, my checkins collection has this structure:
{ Suburb:,
City:,
Leaderboard:}

The leaderboard entry is a boolean to mark if the check in has already been added to the leaderboard.
What I want to do is query for all results where leaderboard is false, count the entries for all cities, count the entries for all suburbs, then add the city and suburb data to a separate collection, then update the leaderboard boolean to indicate they've been counted.
exports.updateLeaderboard = functions.pubsub.schedule('30 * * * *').onRun(async context => {
    db.collection('Bears')
    .where('Leaderboard', '==', 'false')
    .get()
    .then(snap =>{
        snap.forEach(x => {
            //Count unique cities and return object SELECT cities,COUNT(*) AS `count` FROM Bears GROUP BY cities
        })
    })
    .then(() => {
        console.log({result: 'success'});
    })
    .catch(error => {
        console.error(error);
    });
})

Unfortunately, I've come to about the limit of my knowledge here and would love some help.

A:

Firebase is meant to be a real-time platform, and most of your business logic is going to be expressed in Functions. Because the ability to query is so limited, lots of problems like this are usually solved with triggers and data denormalization.
For instance, if you want a count of all mentions of a city, then you have to maintain that count at event-time.
// On document create
await firestore()
  .collection("city-count")
  .doc(doc.city)
  .set({
    count: firebase.firestore.FieldValue.increment(1),
  }, { merge: true });

Since it's a serverless platform, it's built to run a lot of very small, very fast functions like this. Firebase is very bad at doing large computations -- you can quickly run in to mb/minute and doc/minute write limits.
Edit: Here is how Firebase solved this exact problem from the perspective of a SQL trained developer https://www.youtube.com/watch?v=vKqXSZLLnHA

