skip to Main Content

I am filtering documents from Firestore in Python from the collection named "students". I am using a Pydantic model for Student that includes a ListField for locations with the Location model and in that location model i am having the id field. Despite having the document in my database for the location id = 1234456, when executing the query below, I am getting an empty list ([]):

query = db.collection("students").where("locations.id", "==", "1234456").get()

Below is my single document structure

{
    name: "tom"
    roll_no: "13024578"
    age: 24
    locations: [
    {
       "id": "1234456",
       "place": "England"
    },
    {
       "id": "432432",
       "place": "Canada"
    }
}

2

Answers


  1. You query is assuming locations is a map, whereas your document’s data shows it is a table. Hence you get nothing back.

    What are you trying to do? Get all students which have a given location’s id among all their locations?
    For this you will have to change your document structure:

    1. Create a sub-collection locations under student with each document being a location {id, place}
    2. Make a collection group query on locations specifyng the id. You will get a list of locations document back
    3. You can deduce the students’id from the previous result, you can then retrieve each student’s data as needed
    Login or Signup to reply.
  2. This condition in your query:

    .where("locations.id", "==", "1234456")
    

    Matches a JSON structure that looks (exactly) like this:

    "locations": {
      "id": "1234456"
    }
    

    And since you don’t have that JSON structure in your document, it doesn’t match the query.


    What you seem to be trying to do is to perform a partial match of an item in an array. That’s not possible with Firestore though. Operators such as == and in look for complete matches, not for partial matches.

    To allow the use-case, add an additional array field to the document with just the location IDs:

    locationIDs: [ "1234456", "432432" ]
    

    Now you can query that field to find the documents with the location ID you want:

    query = db.collection("students").where("locationIDs", "array-contains", "1234456").get()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search