Ojasa Mirai

Ojasa Mirai

Cloud

Loading...

Learning Level

🟢 Beginner🔵 Advanced
🔧 GCP Account Setup⚙️ GCP Compute Overview🚀 Cloud Run Deployment🎯 App Engine Deployment📁 GCP Storage & Hosting🔥 Firebase Hosting🗄️ Firestore Setup⚡ Firestore Realtime💾 Cloud SQL Setup📊 GCP Monitoring🔑 GCP Authentication📈 GCP Scaling & Performance⚡ Firebase Functions💰 GCP Cost Optimization
Cloud/Gcp Deployment/Firestore Setup

🗄️ Firestore Setup

Introduction

Firebase Firestore is a cloud-hosted, flexible NoSQL database that scales automatically. It offers real-time synchronization, offline support, and powerful querying capabilities for modern web and mobile applications.

Key Learning Outcomes

By the end of this lesson, you'll understand:

  • What Firestore is and when to use it
  • Creating a Firestore database in Firebase project
  • Understanding collections and documents
  • Basic CRUD operations (Create, Read, Update, Delete)
  • Data types and schema design
  • Querying and filtering documents
  • Indexing for performance
  • Best practices for data organization

Getting Started with Firestore

Step 1: Create Firestore Database

firebase init firestore

Step 2: Install Firebase SDK

npm install firebase

Step 3: Initialize Firestore

JavaScript:

import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';

const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  projectId: "your-project"
};

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

export default db;

Python:

import firebase_admin
from firebase_admin import credentials, firestore

cred = credentials.Certificate('serviceAccountKey.json')
firebase_admin.initialize_app(cred)
db = firestore.client()

CRUD Operations

Create (Add Document)

JavaScript:

import { collection, addDoc, setDoc, doc } from 'firebase/firestore';

// Auto-generated ID
const docRef = await addDoc(collection(db, 'users'), {
  name: 'Alice',
  email: 'alice@example.com',
  age: 30
});

// Specific ID
await setDoc(doc(db, 'users', 'user123'), {
  name: 'Bob',
  email: 'bob@example.com'
});

Python:

db.collection('users').add({
    'name': 'Alice',
    'email': 'alice@example.com'
})

db.collection('users').document('user123').set({
    'name': 'Bob',
    'email': 'bob@example.com'
})

Read (Get Document)

JavaScript:

import { doc, getDoc, collection, getDocs } from 'firebase/firestore';

// Get single document
const userRef = doc(db, 'users', 'user123');
const docSnap = await getDoc(userRef);

if (docSnap.exists()) {
  console.log('User:', docSnap.data());
}

// Get all documents
const snapshot = await getDocs(collection(db, 'users'));
snapshot.forEach((doc) => {
  console.log(doc.id, '=>', doc.data());
});

Python:

doc = db.collection('users').document('user123').get()
if doc.exists:
    print('User:', doc.to_dict())

docs = db.collection('users').stream()
for doc in docs:
    print(doc.id, '=>', doc.to_dict())

Update (Modify Document)

JavaScript:

import { updateDoc, doc, increment } from 'firebase/firestore';

await updateDoc(doc(db, 'users', 'user123'), {
  age: 31,
  updatedAt: new Date()
});

// Increment field
await updateDoc(doc(db, 'users', 'user123'), {
  points: increment(10)
});

Python:

db.collection('users').document('user123').update({
    'age': 31,
    'updatedAt': firestore.SERVER_TIMESTAMP
})

Delete (Remove Document)

JavaScript:

import { deleteDoc, doc } from 'firebase/firestore';

await deleteDoc(doc(db, 'users', 'user123'));

Python:

db.collection('users').document('user123').delete()

Querying Documents

JavaScript:

import { query, where, getDocs, orderBy, limit, collection } from 'firebase/firestore';

// Filter query
const q = query(
  collection(db, 'users'),
  where('age', '>=', 30)
);
const snapshot = await getDocs(q);

// Multiple filters
const q2 = query(
  collection(db, 'users'),
  where('age', '>=', 30),
  where('isActive', '==', true),
  orderBy('createdAt', 'desc'),
  limit(10)
);

Python:

docs = db.collection('users').where('age', '>=', 30).stream()

docs = db.collection('users')\
    .where('age', '>=', 30)\
    .where('isActive', '==', True)\
    .order_by('createdAt', direction=firestore.Query.DESCENDING)\
    .limit(10)\
    .stream()

Security Rules

firestore.rules:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
      allow read, write: if request.auth.uid == userId;
    }
    match /posts/{document=**} {
      allow read: if true;
      allow write: if request.auth != null;
    }
  }
}

Batch Operations

JavaScript:

import { writeBatch } from 'firebase/firestore';

const batch = writeBatch(db);

batch.update(doc(db, 'users', 'user123'), { points: increment(100) });
batch.update(doc(db, 'posts', 'post1'), { likes: increment(1) });

await batch.commit();

Key Takeaways

  • **Firestore** is a flexible NoSQL database with automatic scaling
  • **Collections and documents** organize data hierarchically
  • **CRUD operations** are simple and consistent across SDKs
  • **Real-time synchronization** keeps data fresh across clients
  • **Querying** supports filtering, sorting, and limiting
  • **Security rules** control access to collections and documents
  • **Batch operations** ensure atomicity across multiple updates

Next Steps

Learn about Firestore real-time updates for live data synchronization, or explore Cloud Functions for server-side logic.


Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep • Build Real • Verify Skills • Launch Forward

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn