Welcome back! In the previous lessons, you learned how to structure and add data to your Firestore database using collections and documents. Today, we will focus on retrieving data from Firestore. Data retrieval is a fundamental part of working with any database, as it allows you to access and use the information you have stored. In this lesson, we will cover how to fetch a single document by its ID and how to retrieve multiple documents by their IDs. By the end of this session, you will be able to efficiently access the data you need from your Firestore collections.
Retrieving a document from Firestore is straightforward when you know the document's ID. For example, suppose you have a movies collection and want to fetch the document with the ID the-big-new-movie-2016. Here's how you can do it:
Output (example):
If you only need specific fields from the document, you can use the field_paths parameter to select them:
Output (example):
This approach allows you to minimize the amount of data transferred and focus only on the information you need.
Sometimes, you may need to fetch several documents at once, given their IDs. Firestore provides a convenient way to do this using the get_all method on the Firestore client. You simply create references to each document you want to retrieve and pass them to the method. Here's an example:
Output (example):
Note that get_all is a method on the Firestore client (db), not on a collection. This method allows you to efficiently retrieve multiple documents in a single request, even if they're from different collections, as long as you know their document references.
