how to remove elements from array in firestore with a where clause in python

Viewed 716

I've a sample collection in my firestore enter image description here

I've got two arrays in a document. I want to delete the whole array dictionary from two arrays if monthName is January.

Desired output enter image description here

I've tried

doc_ref = db.collection('calender').where('monthName', 'array_contains', 'January').arrayremove()

But I'm getting an error

AttributeError: 'Query' object has no attribute 'arrayRemove'

I referred the documentation, but I couldn't understand that to this problem. So, looking for help here.

2 Answers

Firestore doesn't have the concept of an update query, where you send a condition and an operation to the database. You'll instead have to:

  1. Execute the query to get all documents matching your condition.
  2. Loop over the documents in your Python code.
  3. Then remove the array from each document with an update call.

In addition, arrayRemove can only be used if you know the exact, complete item to remove from the array, you will have to:

  1. Load the document (same as above).
  2. Get the array, and remove the item.
  3. Write the entire remaining array back to the database.

You can create a firestore index to query for documents without knowing their IDs. If you create an index on calender on the fields month1 and month2, your CollectionGroup query would run successfully with (in pseudocode):

objectToDelete = {id: 1, monthName: "January"}

for month in ["month1", "month2"]:
  matchingDocRefs = db.collection("calender")
                   .where(month, "array-contains", objectToDelete)
                   .get() // Returns a list of matching DocumentReferences
  for documentRef in matchingDocRefs:
      documentRef.update({ month, firestore.ArrayRemove(objectToDelete)})

Tested and working in JavaScript.

REFERENCES:

P.S., it's spelled "calendar", not "calender"

Related