1

The documents in my collection have an id (of course), but also a field in which the same id is kept. Question : is it faster to retrieve that document by its id

collection.doc(id).get().then(....)

or by a query

collection.where('id', '==', id).get().then(...)

I just refactored my functions-code. I used to use a query, but now I'm using the id of the document in the collection directly. But I have the impression that this direct method takes longer. I just wonder if that is just an impression ...

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Erwin
  • 11
  • 3

1 Answers1

1

In theory, there is no difference in performance between the two. Firestore queries scale with the number of documents returned by the query. If both queries return 1 document, then they should perform the same. They are essentially both using an index to find a unique value.

See: Queries scale with the size of your result set, not the size of your data set

If you really want a micro-benchmark on this, you should perform your own tests to find out which is faster. But I think you'll be spending a lot of time optimizing something that doesn't need to be optimized. You can decide for yourself if that's worth your time.

My opinionated advice: Instead of worrying about performance, you should worry about clarity of your code. Which one makes more sense to you when you read it in the context of your program? Usually a single get on a document reference is shorter and easier to read, and doesn't require you to look at an array of document results when you expect only one document, but your opinion might be different.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • Thanks for you answer, but I *do* need to worry about performance, because now I got a time-out (function takes more than 60 seconds), which I didn't have using a query. – Erwin Jul 23 '23 at 14:04
  • Neither one of those will take 60 seconds under normal circumstances. They should happen in a small fraction of a second assuming the client has already connected and network conditions are good. If you are deeply concerned about the performance of that fraction of a second, you should perform your own benchmarks. – Doug Stevenson Jul 23 '23 at 14:06
  • You are right. With some logging I found out that the actual retrieving of the documents is not the problem, only takes fractions of a second as you stated. So, my problem lies elsewhere that causes the delay. So sorry to have bothered everyone and especially you Doug – Erwin Jul 23 '23 at 14:33