0
0
GcpConceptBeginner · 3 min read

What is Collection in Firestore: Simple Explanation and Example

In Firestore, a collection is a group of documents that store related data, similar to a folder holding files. Collections organize your data and allow you to easily find and manage documents within your database.
⚙️

How It Works

Think of a Firestore collection like a folder in a filing cabinet. Each folder holds multiple documents, which are like individual files containing information. Collections help keep your data organized by grouping related documents together.

Each document inside a collection has a unique ID and contains data in key-value pairs, similar to a form with labeled fields. You can add, update, or delete documents within a collection without affecting other collections.

This structure makes it easy to find and manage data, just like knowing which folder to open to find a specific file.

💻

Example

This example shows how to create a collection called users and add a document with user information.

javascript
import { initializeApp } from 'firebase/app';
import { getFirestore, collection, addDoc } from 'firebase/firestore';

const firebaseConfig = {
  apiKey: 'your-api-key',
  authDomain: 'your-auth-domain',
  projectId: 'your-project-id'
};

const app = initializeApp(firebaseConfig);
const db = getFirestore(app);

async function addUser() {
  try {
    const usersCollection = collection(db, 'users');
    const docRef = await addDoc(usersCollection, {
      name: 'Alice',
      email: 'alice@example.com',
      age: 30
    });
    console.log('Document written with ID:', docRef.id);
  } catch (e) {
    console.error('Error adding document:', e);
  }
}

addUser();
Output
Document written with ID: <generated-document-id>
🎯

When to Use

Use collections in Firestore whenever you want to group related pieces of data. For example, if you have an app with users, each user’s data can be stored as a document inside a users collection.

Other common uses include collections for orders, products, or messages. This helps keep your data organized and easy to query.

Collections are especially useful when your app needs to handle many similar items, like a list of blog posts or customer records.

Key Points

  • A collection is a container for documents in Firestore.
  • Documents inside collections store data as key-value pairs.
  • Collections help organize and structure your database.
  • You can add, update, or delete documents independently within collections.
  • Collections can contain subcollections for deeper data organization.

Key Takeaways

A Firestore collection groups related documents like a folder holds files.
Documents inside collections store data in simple key-value pairs.
Use collections to organize data for easy access and management.
Collections can have subcollections for more detailed data structure.
Adding or updating documents in a collection does not affect others.