Select by contains and deleting documents from Firestore in a Python environment

Delete Documents from Firestore using Python

For deleting documents from Firestore in a Python environment, you'll typically use the Firebase Admin SDK. Below is a step-by-step guide to set it up and delete documents that you've obtained through a stream:

  • Setup: Make sure you have the Firebase Admin SDK installed and initialized in your Python environment.
  • Stream Documents: Use a Firestore query to stream documents from a collection.
  • Delete Documents: Iterate over the streamed documents and delete each one using its reference.

First, ensure you have Firebase Admin SDK installed:

pip install firebase-admin

Here's a Python script that demonstrates these steps:

import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore

# Initialize the Firebase Admin SDK
cred = credentials.Certificate('path/to/your/serviceAccountKey.json')

db = firestore.client()

# Stream documents from a specific collection
docs = db.collection('yourCollectionName').stream()

for doc in docs:
        # Each 'doc' is a DocumentSnapshot
        doc_ref = db.collection('yourCollectionName').document(
        # Delete the document
        print(f'Document {} successfully deleted')
    except Exception as e:
        print(f'Error deleting document {}: {e}')

Important Notes:

  • Replace 'path/to/your/serviceAccountKey.json' with the path to your Firebase service account key file.
  • Replace 'yourCollectionName' with the name of your Firestore collection.
  • This script assumes you have a Firestore collection from which you're streaming documents and then deleting them. Be very cautious with this operation to avoid unintended data loss.

Proceed with caution and ensure you're deleting the correct documents, especially in a production environment. 😄

Select contains string

This Python class is designed to send messages from a queue. It initializes Firebase Admin SDK, connects to Firestore, and processes documents within a specified range in the 'clicks' collection.

<!-- Code snippet starts -->
class Command(BaseCommand):
    def handle(self, *args, **options):
        cred = credentials.Certificate("firebasekey.json")
        db = firestore.client()
        now =
        start_date = datetime(now.year, now.month, 1)
        end_date = now
        day_count = (end_date - start_date).days + 1
        collection = db.collection('clicks').where("id", '>=', "fgfcfgbaf_ve").where("id", '<=', "fgfcfgbaf_ve" + "\uf8ff")
        docs =
        all_docs = []
        import pdb;pdb.set_trace()
        for doc in docs:
            dic = doc.to_dict()
            doc_ref = db.collection("clicks").document(
<!-- Code snippet ends -->

Note: This code includes a breakpoint for debugging purposes using pdb.set_trace(). Be cautious when running this code in a production environment.