find all documents with same id in different collections in firestore

Viewed 313

I have this structure in firestore. Many collections with id the user_id and inside each of them many documents with IDs the date of departure. The documents contain the fields "from" and "to" with the airport name. I want to retrieve all the IDs of collections (the users IDs) that have the same documents of a choosed user in input for see who shared the flight with this user in all the flights he made. I'm using python.

UPDATE: I solved my issue in this way.

@app.route('/infos/<string:user_id>/', methods=['GET'])
def user_info(user_id):
    docs = db.collection(f'{user_id}').stream()
    travels = []
    for doc in docs:
        sharing_travellers = []
        tmp = doc.to_dict()
        tmp['date'] = doc.id
        colls = db.collections()
        for coll in colls:
            if coll.id != user_id:
                date = datetime.strptime(doc.id, '%Y-%m-%d')
                query = db.collection(f'{coll.id}').stream()
                for q in query:
                    other_date = datetime.strptime(q.id, '%Y-%m-%d')
                    if abs((date - other_date).days) < 1:
                        json_obj = q.to_dict()
                        if json_obj['from'] == tmp['from'] and json_obj['to'] == tmp['to']:
                            sharing_travellers.append(coll.id)
        tmp['shared'] = sharing_travellers
        travels.append(tmp)
    return render_template('user_info.html', title=user_id, travels=travels)
2 Answers

The only way to read across collections is if those collections have the same name. If that was the case, you could use a collection group query.

Since your collections don't have the same name though, you'll have to get the list collections, and then look in each collection separately.

I support Frank's answer but I want to elaborate that it might be wise to reformat the structure of your database to better accommodate this type of situation. cross collection searching is limited to collection group queries which are already limited, and additional methods will require costly solutions.

It's often better to have a dedicated collection with those ID as field values of which you can query per user and in a collective group.

Related