skip to Main Content

What’s the difference between querying firestore using .where() and looking up a specific doc.id?

say I can choose to structure my collection in 2 ways:

  1. collection1 that has doc.id = myspecificIDstring
    I can query like db.collection('collection1').doc('myspecificIDstring')

  2. collection2 that has a field called "theID":"myspecificIDstring"
    I can query like db.collection('collection2').where('theID','==','myspecificIDstring')

are there any differences in reads / performance? I’m trying to decide how to structure my backend

I’ve tried both ways and they are seemingly the same.

2

Answers


    • .doc('myspecificIDstring'): This method provides a direct reference to the document, resulting in a single read operation to retrieve the specified document. It is efficient for fetching a known document quickly.

    • .where('theID', '==', 'myspecificIDstring'): This method performs a query and incurs a read operation on the entire collection. Firestore indexes are used to efficiently narrow down the results to documents matching the specified condition. If you have an index on the ‘theID’ field, the performance should be reasonable. However, querying a large collection without an appropriate index may lead to increased latency and higher costs.

    So, .doc is more efficient.

    Login or Signup to reply.
  1. If the query also matches only a single document, there is no significant performance difference between the two methods of loading a single document.

    This is because Firestore will in both cases use the same approach to load the document: looking up either the document ID or the query value in the relevant index, and then loading the document that matches it.

    I’d usually pick the first approach, but that is for reasons of code clarity, not for a possible difference in performance.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search