Created
January 18, 2024 19:14
-
-
Save LuchoLopez/c649dbfc01703a3828a40a2a08ac34ba to your computer and use it in GitHub Desktop.
Firebase - Firestore collection - Using wildcards
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def replace_wildcards(db_client, collection_path: str): | |
""" | |
Returns a generator with all the elements paths matching the collection expression. | |
Wildcards are allowed: So, you can use 'user/*/collection/*/subcollection/*' to retrieve all the | |
documents matching that expression. | |
""" | |
collection_parts = collection_path.split('*') | |
if len(collection_parts) == 1: | |
yield collection_parts[0] | |
else: | |
to_replace = collection_parts[0].rstrip('/') | |
documents = db_client.collection(to_replace).list_documents() | |
for element in documents: | |
new_collection_path = f"{element.path}/{'*'.join(collection_parts[1:])}".replace('//', '/') | |
is_collection = len(new_collection_path.rstrip('/*').split('/')) % 2 != 0 | |
if is_collection: | |
yield from self.replace_wildcards(new_collection_path) | |
else: | |
yield new_collection_path.rstrip('/') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment