Welcome back! In our previous lessons, we've explored the essentials of Firestore, including its flexible data model based on collections and documents. Today, we will focus on how to add data to Firestore collections. You will learn how to create new documents, add multiple documents efficiently, and handle common scenarios when writing data.
For our examples, we'll use a students collection, where each document represents a student with the following fields: student_id, name, age, and major. Here's a quick look at the kind of data we'll be working with:
| student_id | name | age | major |
|---|---|---|---|
| 1 | Alice | 20 | Computer Science |
| 2 | Bob | 22 | Mathematics |
Let's get started by adding new student records and exploring how Firestore manages these data operations.
To add a new student, such as John, who is studying Physics, to the students collection, you create a new document with the relevant fields. In Firestore, you can either let Firestore generate a unique document ID or specify your own.
Here's how you can add John's details with a specific document ID (using student_id as the document ID):
In this example, the set() method is used to create or overwrite a document in the students collection with the ID '3'. The data is provided as a dictionary, where each key corresponds to a field in the document.
This approach is straightforward and effective for adding individual documents, especially when you want to control the document ID.
Considerations:
- Document Size Limits: Each document in Firestore can be up to 1 MiB in size.
- Overwriting: Using
set()with a document ID will overwrite the document if it already exists, unless you specify otherwise.
If you need to add several students at once, Firestore provides batched writes, which allow you to perform multiple write operations in a single request. This is efficient and helps ensure that all operations in the batch succeed or fail together.
Here's how you can add multiple students using a batch:
In this example, a batch is created, and the set() operation is queued for each new student document. The commit() method sends all the operations to Firestore in a single request.
Limitations and Error Handling:
- Maximum Operations: Each batch can include up to 500 write operations.
- Atomicity: All operations in a batch are committed together; if any operation fails, none are applied.
- Error Handling: If the batch fails, an exception is raised, and you may need to retry the operation.
