<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Paul Meagher on Medium]]></title>
        <description><![CDATA[Stories by Paul Meagher on Medium]]></description>
        <link>https://medium.com/@paulmeagher?source=rss-dcbe60296390------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XL8jL9iPLbosyWZdEhSyhQ@2x.jpeg</url>
            <title>Stories by Paul Meagher on Medium</title>
            <link>https://medium.com/@paulmeagher?source=rss-dcbe60296390------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 06:36:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@paulmeagher/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Adding a new field to a large collection in Firestore.]]></title>
            <link>https://medium.com/@paulmeagher/adding-a-new-field-to-a-large-collection-in-firestore-617336d6d6a3?source=rss-dcbe60296390------2</link>
            <guid isPermaLink="false">https://medium.com/p/617336d6d6a3</guid>
            <category><![CDATA[firestore]]></category>
            <category><![CDATA[cloud-firestore]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Paul Meagher]]></dc:creator>
            <pubDate>Mon, 23 Jan 2023 11:39:13 GMT</pubDate>
            <atom:updated>2023-03-26T15:16:31.882Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wa1UkqIWSE23xEaS.jpg" /><figcaption>Cloud Firestore — Add a new field to all documents in collection.</figcaption></figure><p>Adding a new field to all documents in a large collection in Firestore can be challenging, in this post I’ll describe a method that will make the process simple, efficient and scalable.</p><p>But first, what’s the problem? The simplest approach to adding a new field to every document in a collection probably looks something like this:</p><pre>from google.cloud import firestore<br><br>def add_field_to_collection(collection_name, field_name, field_value):<br>    # Initialize Firestore client<br>    db = firestore.Client()<br><br>    # Get a reference to the collection<br>    collection_ref = db.collection(collection_name)<br><br>    # Get all documents in the collection<br>    docs = collection_ref.get()<br><br>    # Update each document to add the new field<br>    for doc in docs:<br>        doc_ref = doc.reference<br>        doc_ref.update({field_name: field_value})<br><br># Usage example<br>add_field_to_collection(&quot;users&quot;, &quot;isAdmin&quot;, False)</pre><p>In this code snippet we simply load all documents from the collection into memory and one by one update the document with the new field and value.</p><p>This may work where the number of documents is manageable but in very large collections it breaks down for two reasons:</p><ol><li>You’re loading every single document from your collection into memory all at the same time with the collection_ref.get() call.</li><li>You’re making a network request for every single document.</li></ol><p>These two problems make the simple code above unworkable. It would likely fail trying to load that many documents at once and further the latency of a 1–2 second network call for every single document is inefficient in the extreme.</p><p>So how do we make it better?</p><h3>Introducing Pages, Cursors and Batches</h3><p><strong>Pages &amp; Cursors</strong></p><p>When querying a Firebase collection you can use some combination of an <em>order by</em> clause (to ensure a consistent order to the documents), a <em>where</em> clause (to filter based off field values) and a <em>limit</em> clause (to set the page size).</p><p>Let’s keep it simple and just focus on the limit clause, heres an example:</p><pre>query = collection_ref.order_by(&quot;__name__&quot;).limit(20)<br>docs = query.get()</pre><p>This will return a <em>page</em> of 20 results, let’s call this page 1. The next question becomes how do I get page 2? Well — We use whats called a <strong>cursor</strong>. The cursor marks the beginning of the next page, and handily enough we can use a document as a cursor (remember we ordered the entire collection by “name” so the order will always be the same.)</p><p>So to get page 2 we would do something like:</p><pre><br># Set a consistent page size and ordering of the collection.<br>query = collection_ref.order_by(&quot;__name__&quot;).limit(20)<br><br># Get the first page.<br>first_page = query.get()<br><br># Get the next page, using the last document of the previous page as cursor.<br>next_page = query.start_after(first_page[-1]).get()</pre><p>Note: A handy way to get the last value of an array in Python is to use the index [-1].</p><p>Great that’s cursors, we can now move through our collection one page at a time instead of loading all documents at once.</p><p><strong>Streaming</strong></p><p>Alternative approach to paging; you could also use a concept called <strong>streaming </strong>to avoid loading all documents into memory at once. Heres a quick example:</p><pre>collection_ref = db.collection(collection_name)<br><br># Returns an iterable that returns one document at a time.<br>docs = collection_ref.stream()<br><br>for doc in docs:<br>    doc_ref = doc.reference<br>    batch.update(doc_ref, {field_name: field_value})</pre><p>The above snippet allows you to walk through your collection one document at a time however it results in two network calls each iteration (one to get next document and one to update it). This creates an inefficiency and so we will stick with pages and cursors however if your dataset wasn’t super large or you don’t mind the network load this is a slightly simpler approach than the pagination.</p><p><strong>Batches</strong></p><p>The next problem we have is the number of network calls. We don’t want to make a request every single iteration of our loop, as network calls are slow and blocking and introduce latency.</p><p>Ideally we would queue up a few operations and apply them in one request rather than one request per operation. This is where <strong>batches</strong> come in. A batch basically allows you to batch up to 500 operations into a batch and then <em>commit</em> them all at once with one request. This can dramatically improve efficiency if you were previously having a request for every operation.</p><p>Heres an example of how batches work:</p><pre><br>docs = db.collection(collection_name).get()<br><br># Intialise a new batch<br>batch = db.batch()<br><br>for doc in docs:<br>    doc_ref = doc.reference<br>    <br>    # Apply operations to batch.<br>    batch.update(doc_ref, {field_name: field_value})<br><br># Commit the batch.<br>batch.commit()</pre><p>Note: The max batch size is 500, so if you have more than 500 documents you need to handle this.</p><h3>Bringing it all together (TLDR)</h3><p>Okay so we have basically introduced paging or batching on both the read side and the write side. Lets say we pick a page size of 100, this means for every 100 documents we reduce the number of requests going over the network from 200 to 2 🚀.</p><p>Code should take 1% of the previous run time ( if it ran at all).</p><p>Here’s a snippet that uses both concepts to add a new field with a value to every document in a collection efficiently.</p><pre>def add_field_to_collection(collection_ref, field_name, field_value, batch_size=100):<br>    total = 0<br>    query = collection_ref.order_by(&quot;__name__&quot;).limit(batch_size)<br>    docs = query.get()<br>    <br>    # Create a batch write object<br>    batch = db.batch()<br>    i = 0<br>    while docs:<br>        for doc in docs:<br>            doc_ref = doc.reference<br>            batch.update(doc_ref, {field_name: field_value})<br>            i += 1<br>            <br>        if i % batch_size == 0:<br>            <br>            # Commit the batch write every batch_size documents<br>            batch.commit()<br>            <br>            # Create a new batch<br>            batch = db.batch()<br>            <br>        # Get the next batch of documents<br>        query_iterator = query.start_after(docs[-1])<br>        docs = query_iterator.get()<br>        <br>    # Commit the final batch of remaining documents<br>    if i % batch_size != 0:<br>        batch.commit()</pre><p>and we can the go back to our earlier example:</p><pre>add_field_to_collection(db.collection(&quot;users&quot;), &quot;isAdmin&quot;, False, batch_size=100)</pre><p>So there you go: How to add a new field to all documents in an extremely large collection.</p><p>Please let me know if it helps, this is my first ever blogpost!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=617336d6d6a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>