skip to content

In Cloud Firestore, how do documents, collections and subcollections fit together, and what happens to a subcollection when its parent document is deleted?

level: juniorimportance: must knowfreq 68%

answer

  1. alternating path segments
  2. a collection holds only documents
  3. 1 MiB ceiling per document
  4. queries read one collection's documents
  5. what a parent delete leaves behind

basics

~20 s

Firestore keeps fields in documents of up to 1 MiB, documents in collections, and lets a document own subcollections, so paths alternate collection and document. Deleting a document leaves its subcollections in place; they must be deleted separately.

solid answer

~40 s

A document is Firestore's unit of storage: a named set of fields (strings, numbers, booleans, timestamps, geo points, blobs, arrays and maps) capped at 1 MiB. Documents live in collections, and a collection holds only documents, never raw fields or other collections. A document can own subcollections, so a path always alternates, as in `projects/apollo/tasks/t42/comments/c1`, and a collection exists as soon as its first document is written. Two consequences come up in interviews: queries are shallow, so reading `tasks` never pulls in each task's `comments`; and deleting `projects/apollo` does **not** delete `projects/apollo/tasks`. Those documents stay readable by their full paths until your own code deletes them.

code

kotlin · 12 lines
kotlin
import com.google.firebase.Firebase
import com.google.firebase.firestore.firestore

val db = Firebase.firestore

// projects/{projectId}/tasks/{taskId}/comments/{commentId}
val task = db.collection("projects").document("apollo")
    .collection("tasks").document("t42")
val comments = task.collection("comments")

// Deleting the task document leaves every document in `comments` in place.
fun deleteTaskOnly() = task.delete()

go deeper

for a junior

Recall the alternating collection-and-document path, the 1 MiB document limit, and that deleting a parent leaves its subcollections behind.

for a middle

Explain why Firestore queries are shallow, how a collection group query reaches across parents, and why it needs a collection-group-scope index first.

for a senior

Show that you plan deleting a project's whole subtree from trusted server code in batches, and keep documents small so reads and listeners stay cheap.

for a principal

Weigh the benefits of deep hierarchy against shallow queries, orphaned subtrees and the 1 MiB ceiling, then set team conventions for paths, IDs and cleanup.

## The document is the unit of storage Cloud Firestore is a NoSQL **document database**. A **document** is a named record holding **fields**, each mapping a name to a value. Supported values include booleans, numbers, strings, timestamps, geo points, binary blobs, **arrays** and nested objects called **maps**. Documents look a lot like JSON, but they carry extra types and a hard size limit. Firestore is **schemaless**: two documents in the same collection may hold different fields. The documentation still advises keeping the same fields and types across a collection, because that makes the documents easier to query. The limits that shape every design: - a document can be at most **1 MiB (1,048,576 bytes)**; - a document's full name (its path) can be at most **6 KiB**; - maps and arrays can nest at most **20** levels inside one document; - a single field value can be at most 1 MiB minus 89 bytes. The guide describes Firestore as *optimized for storing large collections of small documents*. That sentence is the design rule in miniature. ## Collections and the alternating path A **collection** is a container for documents and nothing else. It cannot hold raw fields, and it cannot directly contain another collection. You do not create a collection explicitly. It appears when its first document is written and disappears when its last document is deleted. Every document is identified by its location, so paths always **alternate**: collection, document, collection, document. You cannot reference a collection inside a collection or a document inside a document. In client code there are two distinct reference types: - `CollectionReference`, used to query or add documents; - `DocumentReference`, used to read, write or delete one document. Creating a reference performs **no network operation**. It is only a pointer, and it is valid whether or not data exists there. Document IDs can be your own keys, such as a user ID, or automatic IDs. An ID must be valid UTF-8 and no longer than 1,500 bytes. It cannot contain `/`, cannot be `.` or `..`, and cannot match `__.*__`. ## Subcollections in a team task-list app Take a team task app with projects, tasks and comments. A natural layout is: ```kotlin val db = Firebase.firestore val comment = db.collection("projects").document("apollo") .collection("tasks").document("t42") .collection("comments").document("c1") // The same reference, built from a slash-separated path: val same = db.document("projects/apollo/tasks/t42/comments/c1") ``` A **subcollection** is a collection attached to one document. Here each task owns its `comments`. Subcollections can nest up to **100** levels deep. They keep the parent small: a task document does not grow with every comment, and comments can be paged and listened to separately. The general trade-off between embedding and referencing belongs to document modelling as a whole. What is specific to Firestore is the 1 MiB ceiling and the fact that every read downloads a whole document. ## Queries are shallow A Firestore query returns documents from **one collection** (or one collection group), and it returns **whole documents**. It never includes subcollection data. Reading `projects/apollo/tasks` returns task documents only. Each task's `comments` need their own query. To search across parents, use a **collection group query**: `db.collectionGroup("comments")` covers every collection whose ID is `comments`, wherever it sits. If that query filters or orders, it needs an index with **collection-group scope**, because automatic indexes are maintained only at collection scope by default. Whether a client may run the query at all is a matter for the security rules, covered with that topic. ## Deleting a parent does not cascade This is the behaviour interviewers probe most. The Firestore guide warns that **deleting a document does not delete its subcollections**. After deleting `projects/apollo`, the documents under `projects/apollo/tasks` and their comments still exist and stay readable by their full paths, even though the parent no longer does. To delete a project completely you must: 1. list the documents in each subcollection, at every level; 2. delete them, in reasonably sized batches; 3. delete the parent document. For large subtrees, run this from trusted server code. The guidance on batched writes recommends server client libraries for bulk data operations, not a mobile SDK. | Limit | Value | |---|---| | Document size | 1 MiB (1,048,576 bytes) | | Document name | 6 KiB | | Subcollection depth | 100 | | Map or array nesting in one document | 20 | | Document or collection ID | 1,500 bytes, no `/` | ## What a weak answer gets wrong - It assumes a delete cascades the way a file-system folder delete does. - It treats a collection as a table with columns that every document must match. - It expects a read of `tasks` to include each task's `comments`. - It grows one document forever, for example an unbounded comments array, until a write hits the 1 MiB limit. - It uses sequential IDs such as `task1`, `task2`. Firestore scatters automatic IDs to avoid hotspots, and the best-practices guide warns against monotonically increasing IDs.

  • Why store a task's comments in a subcollection rather than an array field on the task document?
    A read always downloads the whole document, and a document is capped at 1 MiB. An unbounded comment array makes every task read heavier and eventually fails the write. A `comments` subcollection keeps the task small, lets comments be paged with their own query and listener, and lets each comment be written without rewriting the task.
  • How do you find every comment one member wrote across all tasks and projects?
    Use a collection group query: `db.collectionGroup("comments").whereEqualTo("authorId", uid)`. It covers every collection whose ID is `comments`. Because it filters, it needs a single-field index with collection-group scope on `authorId`. Automatic indexes are maintained only at collection scope by default, so the first run fails with an error that links to creating the index.
  • Why prefer automatic document IDs over sequential IDs like task1, task2?
    Firestore allocates automatic IDs with a scatter algorithm, so new documents spread across the key range. Monotonically increasing IDs concentrate writes on lexicographically close documents. The best-practices guide calls this hotspotting, and it brings higher latency and contention errors at high write rates. Use `document()` with no argument, or `add()`, unless a natural key such as a user ID already exists.

  • Deleting a project document also deletes its tasks and comments subcollections.
  • A collection can hold fields of its own alongside its documents.
  • Reading the tasks collection also returns each task's comments subcollection.
  • A document can grow without limit as long as each field stays small.
  • You must create a collection explicitly before writing its first document.