Search code examples
pythonfirebasegoogle-cloud-firestoregoogle-cloud-shell

Selectively copy data from one Firestore collection to another


I have a Firestore collection, with further subcollections and fields under it. This is what the structure looks like (Very bad example for firestore)

(collection) company
   - (field) client_list 
   - (field) revenue 
   - subcollection1
   - subcollection2

I want to copy some of the documents in it to another collection (copy_of_company), if certain clients are in it's list. Currently, I wrote the code to copy the individual fields inside the documents, but unable to figure out how to copy the subcollections

I won't be performing this operation often, maybe once a month. How can I accomplish this deep, but selective copy?


Solution

  • There is not one or two line solution for this currently.

    query = (comapny_ref.where(u"client_list", u'array_contains', u'ABCorp'))
    companies = [c for c in query.get()]
    for company in companies:
      copy_of_comapny_ref.document(company.id).set(company._data)
      subcollection1_ref = comapny_ref.document(company.id).collection(u'subcollection1').get()
      for subcollection1 in subcollection1_ref:
        copy_of_comapny_ref.document(conv.id).collection(u'subcollection1').\
                            document(subcollection1.id).set(subcollection1._data)