Matteo Di Nome
Matteo Di Nome

Reputation: 51

Cloud Firestore - how retrieve document infos of nested subcollection?

The firestore db has a structure like this: collection: users documents with id an user_id each document has a sub-collection: games each sub-collection has documents with id a game_id

My problem is that I can't loop over the first collection (---> for user in ref_users:) even my firestore db is already full with data organized like I said. Can someone help me understanding how can I retrieve the infos of these documents? Thanks a lot.

from flask import Flask, render_template
from google.cloud import firestore

db = firestore.Client()


@app.route('/', methods=['GET'])
def index():
    ref_users = db.collection(u'users').get()

    games = []
    for user in ref_users:
        print(f'{user.id} => {user.to_dict()}')
        ref_game = db.collection(u'users').document(f'{user.id}').collection(u'games').get()
        for rg in ref_game:
            print(f'{rg.id} => {rg.to_dict()}')
            tmp = rg.to_dict()
            tmp['game_id'] = rg.id
            tmp['user_id'] = user.id
            games.append(tmp)
    return render_template('game_list.html', title='Game list', games=games)

Upvotes: 2

Views: 510

Answers (1)

vitooh
vitooh

Reputation: 4262

Implemented this code on my side with some minor changes and its working fine. So I think that you are maybe searching for solution to decrease computational complexity. I think that collection_group might be helpful. Please check general documentation and Python reference.

I have created code for the same result as the sample (just index part). It has one loop less:

def index():

    games = []
    ref_game = db.collection_group(u'games').get()
    for rg in ref_game:
        print(f'{rg.id} => {rg.to_dict()}')
        tmp = rg.to_dict()
        tmp['game_id'] = rg.id
        tmp['user_id'] = rg.reference.parent.parent.id
        games.append(tmp)
    return str(games)

I would use more sophisticated name for this subcollection like userGames or something. This is because of the fact that collection_group works on every collection with this name in whole database. If your system with grow, there is a chance that you will use the same name games in some other path not related to this logic. Than it will be included to this collection_group and may cause unexpected issues.

Upvotes: 1

Related Questions