תחילת העבודה עם Cloud Firestore

במדריך הזה מוסבר איך להגדיר את Cloud Firestore, להוסיף נתונים ואז לראות את הנתונים שהוספתם ב-Firebase console.

יצירת מסד נתונים של Cloud Firestore

  1. אם עדיין לא עשיתם זאת, צריך ליצור פרויקט ב-Firebase: בFirebaseמסוף, לוחצים על הוספת פרויקט ופועלים לפי ההוראות שמופיעות במסך כדי ליצור פרויקט ב-Firebase או כדי להוסיף שירותי Firebase לפרויקט Google Cloud קיים.

  2. פותחים את הפרויקט בFirebaseמסוף. בחלונית הימנית, מרחיבים את Build ואז בוחרים באפשרות Firestore database.

  3. לוחצים על יצירת מסד נתונים.

  4. בוחרים מיקום למסד הנתונים.

    אם אי אפשר לבחור מיקום, סימן שהמיקום של משאבי ברירת המחדלGoogle Cloud בפרויקט כבר הוגדר. חלק מהמשאבים בפרויקט (כמו מופע ברירת המחדל Cloud Firestore) חולקים תלות משותפת במיקום, ואפשר להגדיר את המיקום שלהם במהלך יצירת הפרויקט או כשמגדירים שירות אחר שחולק את התלות הזו במיקום.

  5. בוחרים מצב התחלתי ל-Cloud Firestore Security Rules:

    מצב בדיקה

    החשבון הזה מתאים להתחלת העבודה עם ספריות לקוח לנייד ולאינטרנט, אבל כל אחד יכול לקרוא ולשכתב את הנתונים שלכם. אחרי הבדיקה, חשוב לעיין בסעיף הגנה על הנתונים.

    כדי להתחיל להשתמש ב-SDK לאתרים, לפלטפורמות של אפל או ל-Android, בוחרים במצב בדיקה.

    מצב נעילה

    דחיית כל פעולות הקריאה והכתיבה מלקוחות ניידים ומלקוחות אינטרנט. שרתי האפליקציות המאומתים שלכם (C#‎,‏ Go,‏ Java,‏ Node.js,‏ PHP,‏ Python או Ruby) עדיין יכולים לגשת למסד הנתונים.

    כדי להתחיל להשתמש בספריית הלקוח של שרת C#,‏ Go,‏ Java,‏ Node.js,‏ PHP,‏ Python או Ruby, בוחרים במצב נעול.

    הסט הראשוני של Cloud Firestore Security Rules יחול על מסד הנתונים שמוגדר כברירת מחדל Cloud Firestore. אם יוצרים כמה מסדי נתונים לפרויקט, אפשר לפרוס Cloud Firestore Security Rules לכל מסד נתונים.

  6. לוחצים על יצירה.

כשמפעילים את Cloud Firestore, מערכת Cloud API Manager מפעילה גם את ה-API.

הגדרת סביבת הפיתוח

מוסיפים לאפליקציה את התלויות הנדרשות ואת ספריות הלקוח.

Web

  1. פועלים לפי ההוראות להוספת Firebase לאפליקציית האינטרנט.
  2. ‫SDK‏ Cloud Firestore זמין כחבילת npm.
    npm install firebase@11.10.0 --save
    תצטרכו לייבא גם את Firebase וגם את Cloud Firestore.
    import { initializeApp } from "firebase/app";
    import { getFirestore } from "firebase/firestore";

Web

  1. פועלים לפי ההוראות להוספת Firebase לאפליקציית האינטרנט.
  2. מוסיפים את ספריות Firebase ו-Cloud Firestore לאפליקציה:
    <script src="https://www.gstatic.com/firebasejs/11.10.0/firebase-app-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/11.10.0/firebase-firestore-compat.js"></script>
    Cloud Firestore SDK זמין גם כחבילת npm.
    npm install firebase@11.10.0 --save
    תצטרכו להגדיר ידנית את הדרישות של Firebase ושל Cloud Firestore.
    import firebase from "firebase/compat/app";
    // Required for side-effects
    import "firebase/firestore";
‫iOS+

פועלים לפי ההוראות להוספת Firebase לאפליקציית Apple.

משתמשים ב-Swift Package Manager כדי להתקין ולנהל יחסי תלות ב-Firebase.

  1. ב-Xcode, כשהפרויקט של האפליקציה פתוח, עוברים אל File > Swift Packages > Add Package Dependency (קובץ > חבילות Swift > הוספת תלות בחבילה).
  2. כשמוצגת בקשה, מוסיפים את מאגר Firebase Apple platforms SDK:
  3.   https://github.com/firebase/firebase-ios-sdk
      
  4. בוחרים את ספריית Firestore.
  5. אחרי שתסיימו, פלטפורמת Xcode תתחיל באופן אוטומטי לטפל ביחסי התלות ולהוריד אותם ברקע.
Android
  1. פועלים לפי ההוראות להוספת Firebase לאפליקציית Android.
  2. באמצעות Firebase Android BoM, מצהירים על התלות בספרייה Cloud Firestore ל-Android בקובץ Gradle של המודול (ברמת האפליקציה) (בדרך כלל app/build.gradle.kts או app/build.gradle).
    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:33.16.0"))
    
        // Declare the dependency for the Cloud Firestore library
        // When using the BoM, you don't specify versions in Firebase library dependencies
        implementation("com.google.firebase:firebase-firestore")
    }

    אם משתמשים בFirebase Android BoM, האפליקציה תמיד תשתמש בגרסאות תואמות של ספריות Firebase Android.

    (חלופה) מצהירים על תלות בספריית Firebase בלי להשתמש ב- BoM

    אם תבחרו לא להשתמש ב-Firebase BoM, תצטרכו לציין כל גרסה של ספריית Firebase בשורת התלות שלה.

    הערה: אם אתם משתמשים בכמה ספריות Firebase באפליקציה, מומלץ מאוד להשתמש ב-BoM כדי לנהל את גרסאות הספריות, וכך לוודא שכל הגרסאות תואמות.

    dependencies {
        // Declare the dependency for the Cloud Firestore library
        // When NOT using the BoM, you must specify versions in Firebase library dependencies
        implementation("com.google.firebase:firebase-firestore:25.1.4")
    }

    מחפשים מודול ספריות ספציפי ל-Kotlin? החל מגרסת אוקטובר 2023, מפתחי Kotlin ומפתחי Java יכולים להסתמך על מודול הספרייה הראשי (פרטים נוספים זמינים בשאלות הנפוצות בנושא).

Dart

  1. אם עדיין לא עשיתם זאת, מגדירים ומפעילים את Firebase באפליקציית Flutter.
  2. מהרמה הבסיסית (root) של פרויקט Flutter, מריצים את הפקודה הבאה כדי להתקין את הפלאגין:
    flutter pub add cloud_firestore
  3. בסיום התהליך, בונים מחדש את אפליקציית Flutter:
    flutter run
  4. אופציונלי: כדי לקצר את זמני הבנייה ב-iOS וב-macOS, אפשר לכלול את ה-framework שעבר קומפילציה מראש.

    נכון לעכשיו, Firestore SDK for iOS תלוי בקוד שיכול לקחת יותר מ-5 דקות לבנייה ב-Xcode. כדי לקצר משמעותית את זמני הבנייה, אפשר להשתמש בגרסה שעברה קומפילציה מראש. לשם כך, מוסיפים את השורה הבאה לבלוק target 'Runner' do בקובץ Podfile:

    target 'Runner' do
      use_frameworks!
      use_modular_headers!
    
      pod 'FirebaseFirestore',
        :git => 'https://github.com/invertase/firestore-ios-sdk-frameworks.git',
        :tag => 'IOS_SDK_VERSION'
    
      flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
      target 'RunnerTests' do
        inherit! :search_paths
      end
    end

    מחליפים את IOS_SDK_VERSION בגרסה של Firebase iOS SDK שצוינה בקובץ firebase_sdk_version.rb של firebase_core. אם אתם לא משתמשים בגרסה האחרונה של firebase_core, חפשו את הקובץ הזה במטמון המקומי של חבילת Pub (בדרך כלל ~/.pub-cache).

    בנוסף, מוודאים ששדרגתם את CocoaPods לגרסה 1.9.1 ואילך:

    gem install cocoapods

    מידע נוסף זמין בבעיה ב-GitHub.

Java
  1. מוסיפים את Firebase Admin SDK לאפליקציה:
    • באמצעות Gradle:
      compile 'com.google.firebase:firebase-admin:1.32.0'
    • שימוש ב-Maven:
      <dependency>
        <groupId>com.google.firebase</groupId>
        <artifactId>firebase-admin</artifactId>
        <version>1.32.0</version>
      </dependency>
           
  2. כדי לאתחל את Cloud Firestore עם פרטי הכניסה המתאימים בסביבה שלכם, פועלים לפי ההוראות הבאות.
Python
  1. מוסיפים את Firebase Admin SDK לאפליקציית Python:
    pip install --upgrade firebase-admin
  2. כדי לאתחל את Cloud Firestore עם פרטי הכניסה המתאימים בסביבה שלכם, פועלים לפי ההוראות הבאות.
C++‎
  1. פועלים לפי ההוראות להוספת Firebase לפרויקט C++‎.
  2. ממשק C++‎ ל-Android.
    • תלויות ב-Gradle. מוסיפים את השורות הבאות לקובץ Gradle של המודול (ברמת האפליקציה) (בדרך כלל app/build.gradle):
              android.defaultConfig.externalNativeBuild.cmake {
                arguments "-DFIREBASE_CPP_SDK_DIR=$gradle.firebase_cpp_sdk_dir"
              }
      
              apply from: "$gradle.firebase_cpp_sdk_dir/Android/firebase_dependencies.gradle"
              firebaseCpp.dependencies {
                // earlier entries
                auth
                firestore
              }
              
    • תלויות בינאריות. באופן דומה, הדרך המומלצת להשיג את יחסי התלות הבינאריים היא להוסיף את הקוד הבא לקובץ CMakeLists.txt:
              add_subdirectory(${FIREBASE_CPP_SDK_DIR} bin/ EXCLUDE_FROM_ALL)
              set(firebase_libs firebase_auth firebase_firestore firebase_app)
              # Replace the target name below with the actual name of your target,
              # for example, "native-lib".
              target_link_libraries(${YOUR_TARGET_NAME_HERE} "${firebase_libs}")
              
  3. כדי להגדיר שילוב של אפליקציות למחשב, אפשר לעיין במאמר איך מוסיפים את Firebase לפרויקט C++‎.
Unity
  1. פועלים לפי ההוראות להוספת Firebase לפרויקט Unity.
  2. משתמשים בממשק Unity כדי להגדיר את הפרויקט כך שימזער את גרסאות ה-build של Android.
  3. כדי להימנע מההודעה Error while merging dex archives, צריך לבצע מיניפיקציה של ה-build.

    • האפשרות נמצאת בהגדרות הנגן > Android > הגדרות פרסום > צמצום.
    • יכול להיות שהאפשרויות יהיו שונות בגרסאות שונות של Unity, לכן מומלץ לעיין במסמכי התיעוד הרשמיים של Unity ובמדריך לניפוי באגים ב-Firebase Unity Build.
    • אם אחרי הפעלת המיזעור, מספר השיטות שמופיעות בהפניה עדיין חורג מהמגבלה, אפשרות נוספת היא להפעיל את multidex ב:
      • mainTemplate.gradle אם האפשרות Custom Gradle Template (תבנית Gradle מותאמת אישית) מופעלת בקטע Player Settings (הגדרות הנגן)
      • או קובץ build.gradle ברמת המודול, אם משתמשים ב-Android Studio כדי ליצור את הפרויקט המיוצא.
Node.js
  1. מוסיפים את Firebase Admin SDK לאפליקציה:
    npm install firebase-admin --save
  2. כדי לאתחל את Cloud Firestore עם פרטי הכניסה המתאימים בסביבה שלכם, פועלים לפי ההוראות הבאות.
Go
  1. מוסיפים את Firebase Admin SDK לאפליקציית Go:
    go get firebase.google.com/go
  2. כדי לאתחל את Cloud Firestore עם פרטי הכניסה המתאימים בסביבה שלכם, פועלים לפי ההוראות הבאות.
PHP
  1. Cloud Firestore ספריות הלקוח של השרת (Java,‏ Node.js,‏ Python,‏ Go,‏ PHP,‏ C#‎ ו-Ruby) משתמשות ב-Google Application Default Credentials לאימות.
    • כדי לבצע אימות מסביבת הפיתוח, מגדירים את משתנה הסביבה GOOGLE_APPLICATION_CREDENTIALS כך שיצביע על קובץ מפתח של חשבון שירות בפורמט JSON. אפשר ליצור קובץ מפתח בדף פרטי הכניסה של API Console.
      export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
    • בסביבת הייצור, לא צריך לבצע אימות אם מריצים את האפליקציה ב-App Engine או ב-Compute Engine, באמצעות אותו פרויקט שבו משתמשים ב-Cloud Firestore. אם לא, מגדירים חשבון שירות.
  2. מתקינים ומפעילים את התוסף gRPC ל-PHP, שנדרש לשימוש בספריית הלקוח.
  3. מוסיפים לאפליקציה את ספריית Cloud Firestore PHP:
    composer require google/cloud-firestore
C#‎
  1. Cloud Firestore ספריות הלקוח של השרת (Java,‏ Node.js,‏ Python,‏ Go,‏ PHP,‏ C#‎ ו-Ruby) משתמשות ב-Google Application Default Credentials לאימות.
    • כדי לבצע אימות מסביבת הפיתוח, מגדירים את משתנה הסביבה GOOGLE_APPLICATION_CREDENTIALS כך שיצביע על קובץ מפתח של חשבון שירות בפורמט JSON. אפשר ליצור קובץ מפתח בדף פרטי הכניסה של API Console.
      export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
    • בסביבת הייצור, לא צריך לבצע אימות אם מריצים את האפליקציה ב-App Engine או ב-Compute Engine, באמצעות אותו פרויקט שבו משתמשים ב-Cloud Firestore. אם לא, מגדירים חשבון שירות.
  2. מוסיפים את ספריית Cloud Firestore C# לאפליקציה בקובץ .csproj:
    <ItemGroup>
      <PackageReference Include="Google.Cloud.Firestore" Version="1.1.0-beta01" />
    </ItemGroup>
  3. מוסיפים לקובץ Program.cs את הנתונים הבאים:
    using Google.Cloud.Firestore;
Ruby
  1. Cloud Firestore ספריות הלקוח של השרת (Java,‏ Node.js,‏ Python,‏ Go,‏ PHP,‏ C#‎ ו-Ruby) משתמשות ב-Google Application Default Credentials לאימות.
    • כדי לבצע אימות מסביבת הפיתוח, מגדירים את משתנה הסביבה GOOGLE_APPLICATION_CREDENTIALS כך שיצביע על קובץ מפתח של חשבון שירות בפורמט JSON. אפשר ליצור קובץ מפתח בדף פרטי הכניסה של API Console.
      export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
    • בסביבת הייצור, לא צריך לבצע אימות אם מריצים את האפליקציה ב-App Engine או ב-Compute Engine, באמצעות אותו פרויקט שבו משתמשים ב-Cloud Firestore. אם לא, מגדירים חשבון שירות.
  2. מוסיפים את ספריית Cloud Firestore Ruby לאפליקציה בקובץ Gemfile:
    gem "google-cloud-firestore"
  3. מתקינים את יחסי התלות מ-Gemfile באמצעות הפקודה:
    bundle install

(אופציונלי) יצירת אב טיפוס ובדיקה באמצעות Firebase Local Emulator Suite

למפתחי אפליקציות לנייד, לפני שנסביר איך האפליקציה כותבת ל-Cloud Firestore וקוראת ממנו, נציג קבוצה של כלים שבהם אפשר להשתמש כדי ליצור אב טיפוס ולבדוק את הפונקציונליות של Firebase Local Emulator Suite: Firebase Local Emulator Suite.Cloud Firestore אם אתם מנסים מודלים שונים של נתונים, מבצעים אופטימיזציה של כללי האבטחה או מחפשים את הדרך הכי חסכונית ליצור אינטראקציה עם ה-Back-end, כדאי לעבוד באופן מקומי בלי לפרוס שירותים פעילים.

Cloud Firestore אמולטור הוא חלק מ-Local Emulator Suite, שמאפשר לאפליקציה שלכם ליצור אינטראקציה עם התוכן וההגדרות של מסד הנתונים המדומה, וגם עם משאבי הפרויקט המדומים (פונקציות, מסדי נתונים אחרים וכללי אבטחה).

השימוש באמולטור Cloud Firestore מתבצע בכמה שלבים פשוטים:

  1. הוספת שורת קוד להגדרת הבדיקה של האפליקציה כדי להתחבר לאמולטור.
  2. מהספרייה הראשית של פרויקט מקומי, מריצים את הפקודה firebase emulators:start.
  3. ביצוע קריאות מקוד האב-טיפוס של האפליקציה באמצעות Cloud Firestore Platform SDK כרגיל.

כאן אפשר למצוא הסבר מפורט על Cloud Firestore ועל Cloud Functions. מומלץ גם לעיין Local Emulator Suite במבוא.

אתחול Cloud Firestore

מאתחלים מופע של Cloud Firestore:

Web

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

// TODO: Replace the following with your app's Firebase project configuration
// See: https://support.google.com/firebase/answer/7015592
const firebaseConfig = {
    FIREBASE_CONFIGURATION
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);


// Initialize Cloud Firestore and get a reference to the service
const db = getFirestore(app);

מחליפים את FIREBASE_CONFIGURATION ב-firebaseConfig של אפליקציית האינטרנט.

כדי לשמור את הנתונים כשהמכשיר מתנתק, אפשר לעיין במסמכי התיעוד בנושא הפעלת נתונים במצב אופליין.

Web

import firebase from "firebase/app";
import "firebase/firestore";

// TODO: Replace the following with your app's Firebase project configuration
// See: https://support.google.com/firebase/answer/7015592
const firebaseConfig = {
    FIREBASE_CONFIGURATION
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);


// Initialize Cloud Firestore and get a reference to the service
const db = firebase.firestore();

מחליפים את FIREBASE_CONFIGURATION ב-firebaseConfig של אפליקציית האינטרנט.

כדי לשמור את הנתונים כשהמכשיר מתנתק, אפשר לעיין במסמכי התיעוד בנושא הפעלת נתונים במצב אופליין.

Swift
הערה: המוצר הזה לא זמין ב-watchOS וביעדים של קליפים של אפליקציות.
import FirebaseCore
import FirebaseFirestore
FirebaseApp.configure()

let db = Firestore.firestore()
Objective-C
הערה: המוצר הזה לא זמין ב-watchOS ובמטרות של קליפים של אפליקציות.
@import FirebaseCore;
@import FirebaseFirestore;

// Use Firebase library to configure APIs
[FIRApp configure];
  
FIRFirestore *defaultFirestore = [FIRFirestore firestore];

Kotlin

// Access a Cloud Firestore instance from your Activity
val db = Firebase.firestore

Java

// Access a Cloud Firestore instance from your Activity
FirebaseFirestore db = FirebaseFirestore.getInstance();

Dart

db = FirebaseFirestore.instance;
Java
יש דרכים שונות לאתחל את Cloud Firestore SDK בהתאם לסביבה שלכם. בהמשך מפורטות השיטות הנפוצות ביותר. לעיון במאמר המלא בנושא, אפשר לעבור אל הפעלת Admin SDK.
  • הפעלה בתאריך Google Cloud
    import com.google.auth.oauth2.GoogleCredentials;
    import com.google.cloud.firestore.Firestore;
    
    import com.google.firebase.FirebaseApp;
    import com.google.firebase.FirebaseOptions;
    
    // Use the application default credentials
    GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
    FirebaseOptions options = new FirebaseOptions.Builder()
        .setCredentials(credentials)
        .setProjectId(projectId)
        .build();
    FirebaseApp.initializeApp(options);
    
    Firestore db = FirestoreClient.getFirestore();
  • איך מאתחלים בשרת שלכם

    כדי להשתמש ב-Firebase Admin SDK בשרת שלכם, צריך להשתמש בחשבון שירות.

    נכנסים אל IAM & admin > Service accounts במסוף Google Cloud. יוצרים מפתח פרטי חדש ושומרים את קובץ ה-JSON. לאחר מכן משתמשים בקובץ כדי לאתחל את ה-SDK:

    import com.google.auth.oauth2.GoogleCredentials;
    import com.google.cloud.firestore.Firestore;
    
    import com.google.firebase.FirebaseApp;
    import com.google.firebase.FirebaseOptions;
    
    // Use a service account
    InputStream serviceAccount = new FileInputStream("path/to/serviceAccount.json");
    GoogleCredentials credentials = GoogleCredentials.fromStream(serviceAccount);
    FirebaseOptions options = new FirebaseOptions.Builder()
        .setCredentials(credentials)
        .build();
    FirebaseApp.initializeApp(options);
    
    Firestore db = FirestoreClient.getFirestore();
  • Python
    יש דרכים שונות לאתחל את Cloud Firestore SDK בהתאם לסביבה שלכם. בהמשך מפורטות השיטות הנפוצות ביותר. לעיון במאמר המלא בנושא, אפשר לעבור אל הפעלת Admin SDK.
  • הפעלה בתאריך Google Cloud
    import firebase_admin
    from firebase_admin import firestore
    
    # Application Default credentials are automatically created.
    app = firebase_admin.initialize_app()
    db = firestore.client()

    אפשר גם להשתמש בפרטי כניסה קיימים שמוגדרים כברירת מחדל באפליקציה כדי לאתחל את ה-SDK.

    import firebase_admin
    from firebase_admin import credentials
    from firebase_admin import firestore
    
    # Use the application default credentials.
    cred = credentials.ApplicationDefault()
    
    firebase_admin.initialize_app(cred)
    db = firestore.client()
  • איך מאתחלים בשרת שלכם

    כדי להשתמש ב-Firebase Admin SDK בשרת שלכם, צריך להשתמש בחשבון שירות.

    נכנסים אל IAM & admin > Service accounts במסוף Google Cloud. יוצרים מפתח פרטי חדש ושומרים את קובץ ה-JSON. לאחר מכן משתמשים בקובץ כדי לאתחל את ה-SDK:

    import firebase_admin
    from firebase_admin import credentials
    from firebase_admin import firestore
    
    # Use a service account.
    cred = credentials.Certificate('path/to/serviceAccount.json')
    
    app = firebase_admin.initialize_app(cred)
    
    db = firestore.client()
  • Python

    יש דרכים שונות לאתחל את Cloud Firestore SDK בהתאם לסביבה שלכם. בהמשך מפורטות השיטות הנפוצות ביותר. לעיון במאמר המלא בנושא, אפשר לעבור אל הפעלת Admin SDK.
  • הפעלה בתאריך Google Cloud
    import firebase_admin
    from firebase_admin import firestore_async
    
    # Application Default credentials are automatically created.
    app = firebase_admin.initialize_app()
    db = firestore_async.client()

    אפשר גם להשתמש בפרטי כניסה קיימים שמוגדרים כברירת מחדל באפליקציה כדי לאתחל את ה-SDK.

    import firebase_admin
    from firebase_admin import credentials
    from firebase_admin import firestore_async
    
    # Use the application default credentials.
    cred = credentials.ApplicationDefault()
    
    firebase_admin.initialize_app(cred)
    db = firestore_async.client()
  • איך מאתחלים בשרת שלכם

    כדי להשתמש ב-Firebase Admin SDK בשרת שלכם, צריך להשתמש בחשבון שירות.

    נכנסים אל IAM & admin > Service accounts במסוף Google Cloud. יוצרים מפתח פרטי חדש ושומרים את קובץ ה-JSON. לאחר מכן משתמשים בקובץ כדי לאתחל את ה-SDK:

    import firebase_admin
    from firebase_admin import credentials
    from firebase_admin import firestore_async
    
    # Use a service account.
    cred = credentials.Certificate('path/to/serviceAccount.json')
    
    app = firebase_admin.initialize_app(cred)
    
    db = firestore_async.client()
  • C++‎
    // Make sure the call to `Create()` happens some time before you call Firestore::GetInstance().
    App::Create();
    Firestore* db = Firestore::GetInstance();
    Node.js
    יש דרכים שונות לאתחל את Cloud Firestore SDK בהתאם לסביבה שלכם. בהמשך מפורטות השיטות הנפוצות ביותר. לעיון במאמר המלא בנושא, אפשר לעבור אל הפעלת Admin SDK.
    • הפעלה בתאריך Cloud Functions
      const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
      const { getFirestore, Timestamp, FieldValue, Filter } = require('firebase-admin/firestore');
      initializeApp();
      
      const db = getFirestore();
      
    • הפעלה בתאריך Google Cloud
      const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
      const { getFirestore, Timestamp, FieldValue, Filter } = require('firebase-admin/firestore');
      initializeApp({
        credential: applicationDefault()
      });
      
      const db = getFirestore();
    • איך מאתחלים בשרת שלכם

      כדי להשתמש ב-Firebase Admin SDK בשרת שלכם (או בכל סביבת Node.js אחרת), צריך להשתמש בחשבון שירות. נכנסים אל IAM & admin > Service accounts במסוף Google Cloud. יוצרים מפתח פרטי חדש ושומרים את קובץ ה-JSON. לאחר מכן משתמשים בקובץ כדי לאתחל את ה-SDK:

      const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
      const { getFirestore, Timestamp, FieldValue, Filter } = require('firebase-admin/firestore');
      const serviceAccount = require('./path/to/serviceAccountKey.json');
      
      initializeApp({
        credential: cert(serviceAccount)
      });
      
      const db = getFirestore();
      
    Go
    יש דרכים שונות לאתחל את Cloud Firestore SDK בהתאם לסביבה שלכם. בהמשך מפורטות השיטות הנפוצות ביותר. לעיון במאמר המלא בנושא, אפשר לעבור אל הפעלת Admin SDK.
  • הפעלה בתאריך Google Cloud
    import (
      "log"
    
      firebase "firebase.google.com/go"
      "google.golang.org/api/option"
    )
    
    // Use the application default credentials
    ctx := context.Background()
    conf := &firebase.Config{ProjectID: projectID}
    app, err := firebase.NewApp(ctx, conf)
    if err != nil {
      log.Fatalln(err)
    }
    
    client, err := app.Firestore(ctx)
    if err != nil {
      log.Fatalln(err)
    }
    defer client.Close()
  • איך מאתחלים בשרת שלכם

    כדי להשתמש ב-Firebase Admin SDK בשרת שלכם, צריך להשתמש בחשבון שירות.

    נכנסים אל IAM & admin > Service accounts במסוף Google Cloud. יוצרים מפתח פרטי חדש ושומרים את קובץ ה-JSON. לאחר מכן משתמשים בקובץ כדי לאתחל את ה-SDK:

    import (
      "log"
    
      firebase "firebase.google.com/go"
      "google.golang.org/api/option"
    )
    
    // Use a service account
    ctx := context.Background()
    sa := option.WithCredentialsFile("path/to/serviceAccount.json")
    app, err := firebase.NewApp(ctx, nil, sa)
    if err != nil {
      log.Fatalln(err)
    }
    
    client, err := app.Firestore(ctx)
    if err != nil {
      log.Fatalln(err)
    }
    defer client.Close()
  • PHP

    PHP

    מידע נוסף על התקנה ויצירה של לקוח Cloud Firestore זמין במאמר ספריות לקוח של Cloud Firestore.

    use Google\Cloud\Firestore\FirestoreClient;
    
    /**
     * Initialize Cloud Firestore with default project ID.
     */
    function setup_client_create(string $projectId = null)
    {
        // Create the Cloud Firestore client
        if (empty($projectId)) {
            // The `projectId` parameter is optional and represents which project the
            // client will act on behalf of. If not supplied, the client falls back to
            // the default project inferred from the environment.
            $db = new FirestoreClient();
            printf('Created Cloud Firestore client with default project ID.' . PHP_EOL);
        } else {
            $db = new FirestoreClient([
                'projectId' => $projectId,
            ]);
            printf('Created Cloud Firestore client with project ID: %s' . PHP_EOL, $projectId);
        }
    }
    Unity
    using Firebase.Firestore;
    using Firebase.Extensions;
    FirebaseFirestore db = FirebaseFirestore.DefaultInstance;
    C#‎

    C#‎

    מידע נוסף על התקנה ויצירה של לקוח Cloud Firestore זמין במאמר ספריות לקוח של Cloud Firestore.

    FirestoreDb db = FirestoreDb.Create(project);
    Console.WriteLine("Created Cloud Firestore client with project ID: {0}", project);
    Ruby
    require "google/cloud/firestore"
    
    # The `project_id` parameter is optional and represents which project the
    # client will act on behalf of. If not supplied, the client falls back to the
    # default project inferred from the environment.
    firestore = Google::Cloud::Firestore.new project_id: project_id
    
    puts "Created Cloud Firestore client with given project ID."

    הוספת נתונים

    Cloud Firestore מאחסן נתונים במסמכים, שמאוחסנים באוספים. Cloud Firestore יוצר אוספים ומסמכים באופן מרומז בפעם הראשונה שמוסיפים נתונים למסמך. אין צורך ליצור אוספים או מסמכים באופן מפורש.

    יוצרים אוסף ומסמך חדשים באמצעות קוד הדוגמה הבא.

    Web

    import { collection, addDoc } from "firebase/firestore"; 
    
    try {
      const docRef = await addDoc(collection(db, "users"), {
        first: "Ada",
        last: "Lovelace",
        born: 1815
      });
      console.log("Document written with ID: ", docRef.id);
    } catch (e) {
      console.error("Error adding document: ", e);
    }

    Web

    db.collection("users").add({
        first: "Ada",
        last: "Lovelace",
        born: 1815
    })
    .then((docRef) => {
        console.log("Document written with ID: ", docRef.id);
    })
    .catch((error) => {
        console.error("Error adding document: ", error);
    });
    Swift
    הערה: המוצר הזה לא זמין ב-watchOS ובמטרות של קליפים של אפליקציות.
    // Add a new document with a generated ID
    do {
      let ref = try await db.collection("users").addDocument(data: [
        "first": "Ada",
        "last": "Lovelace",
        "born": 1815
      ])
      print("Document added with ID: \(ref.documentID)")
    } catch {
      print("Error adding document: \(error)")
    }
    Objective-C
    הערה: המוצר הזה לא זמין ב-watchOS ובמטרות של קליפים של אפליקציות.
    // Add a new document with a generated ID
    __block FIRDocumentReference *ref =
        [[self.db collectionWithPath:@"users"] addDocumentWithData:@{
          @"first": @"Ada",
          @"last": @"Lovelace",
          @"born": @1815
        } completion:^(NSError * _Nullable error) {
          if (error != nil) {
            NSLog(@"Error adding document: %@", error);
          } else {
            NSLog(@"Document added with ID: %@", ref.documentID);
          }
        }];

    Kotlin

    // Create a new user with a first and last name
    val user = hashMapOf(
        "first" to "Ada",
        "last" to "Lovelace",
        "born" to 1815,
    )
    
    // Add a new document with a generated ID
    db.collection("users")
        .add(user)
        .addOnSuccessListener { documentReference ->
            Log.d(TAG, "DocumentSnapshot added with ID: ${documentReference.id}")
        }
        .addOnFailureListener { e ->
            Log.w(TAG, "Error adding document", e)
        }

    Java

    // Create a new user with a first and last name
    Map<String, Object> user = new HashMap<>();
    user.put("first", "Ada");
    user.put("last", "Lovelace");
    user.put("born", 1815);
    
    // Add a new document with a generated ID
    db.collection("users")
            .add(user)
            .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                @Override
                public void onSuccess(DocumentReference documentReference) {
                    Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId());
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.w(TAG, "Error adding document", e);
                }
            });

    Dart

    // Create a new user with a first and last name
    final user = <String, dynamic>{
      "first": "Ada",
      "last": "Lovelace",
      "born": 1815
    };
    
    // Add a new document with a generated ID
    db.collection("users").add(user).then((DocumentReference doc) =>
        print('DocumentSnapshot added with ID: ${doc.id}'));
    Java
    DocumentReference docRef = db.collection("users").document("alovelace");
    // Add document data  with id "alovelace" using a hashmap
    Map<String, Object> data = new HashMap<>();
    data.put("first", "Ada");
    data.put("last", "Lovelace");
    data.put("born", 1815);
    //asynchronously write data
    ApiFuture<WriteResult> result = docRef.set(data);
    // ...
    // result.get() blocks on response
    System.out.println("Update time : " + result.get().getUpdateTime());
    Python
    doc_ref = db.collection("users").document("alovelace")
    doc_ref.set({"first": "Ada", "last": "Lovelace", "born": 1815})

    Python

    doc_ref = db.collection("users").document("alovelace")
    await doc_ref.set({"first": "Ada", "last": "Lovelace", "born": 1815})
    C++‎
    // Add a new document with a generated ID
    Future<DocumentReference> user_ref =
        db->Collection("users").Add({{"first", FieldValue::String("Ada")},
                                     {"last", FieldValue::String("Lovelace")},
                                     {"born", FieldValue::Integer(1815)}});
    
    user_ref.OnCompletion([](const Future<DocumentReference>& future) {
      if (future.error() == Error::kErrorOk) {
        std::cout << "DocumentSnapshot added with ID: " << future.result()->id()
                  << std::endl;
      } else {
        std::cout << "Error adding document: " << future.error_message() << std::endl;
      }
    });
    Node.js
    const docRef = db.collection('users').doc('alovelace');
    
    await docRef.set({
      first: 'Ada',
      last: 'Lovelace',
      born: 1815
    });
    Go
    _, _, err := client.Collection("users").Add(ctx, map[string]interface{}{
    	"first": "Ada",
    	"last":  "Lovelace",
    	"born":  1815,
    })
    if err != nil {
    	log.Fatalf("Failed adding alovelace: %v", err)
    }
    PHP

    PHP

    מידע נוסף על התקנה ויצירה של לקוח Cloud Firestore זמין במאמר ספריות לקוח של Cloud Firestore.

    $docRef = $db->collection('samples/php/users')->document('alovelace');
    $docRef->set([
        'first' => 'Ada',
        'last' => 'Lovelace',
        'born' => 1815
    ]);
    printf('Added data to the lovelace document in the users collection.' . PHP_EOL);
    Unity
    DocumentReference docRef = db.Collection("users").Document("alovelace");
    Dictionary<string, object> user = new Dictionary<string, object>
    {
    	{ "First", "Ada" },
    	{ "Last", "Lovelace" },
    	{ "Born", 1815 },
    };
    docRef.SetAsync(user).ContinueWithOnMainThread(task => {
    	Debug.Log("Added data to the alovelace document in the users collection.");
    });
    C#‎
    DocumentReference docRef = db.Collection("users").Document("alovelace");
    Dictionary<string, object> user = new Dictionary<string, object>
    {
        { "First", "Ada" },
        { "Last", "Lovelace" },
        { "Born", 1815 }
    };
    await docRef.SetAsync(user);
    Ruby
    doc_ref = firestore.doc "#{collection_path}/alovelace"
    
    doc_ref.set(
      {
        first: "Ada",
        last:  "Lovelace",
        born:  1815
      }
    )
    
    puts "Added data to the alovelace document in the users collection."

    עכשיו מוסיפים עוד מסמך לאוסף users. שימו לב שהמסמך הזה כולל צמד מפתח/ערך (שם אמצעי) שלא מופיע במסמך הראשון. מסמכים באוסף יכולים להכיל קבוצות שונות של מידע.

    Web

    // Add a second document with a generated ID.
    import { addDoc, collection } from "firebase/firestore"; 
    
    try {
      const docRef = await addDoc(collection(db, "users"), {
        first: "Alan",
        middle: "Mathison",
        last: "Turing",
        born: 1912
      });
    
      console.log("Document written with ID: ", docRef.id);
    } catch (e) {
      console.error("Error adding document: ", e);
    }

    Web

    // Add a second document with a generated ID.
    db.collection("users").add({
        first: "Alan",
        middle: "Mathison",
        last: "Turing",
        born: 1912
    })
    .then((docRef) => {
        console.log("Document written with ID: ", docRef.id);
    })
    .catch((error) => {
        console.error("Error adding document: ", error);
    });
    Swift
    הערה: המוצר הזה לא זמין ב-watchOS ובמטרות של קליפים של אפליקציות.
    // Add a second document with a generated ID.
    do {
      let ref = try await db.collection("users").addDocument(data: [
        "first": "Alan",
        "middle": "Mathison",
        "last": "Turing",
        "born": 1912
      ])
      print("Document added with ID: \(ref.documentID)")
    } catch {
      print("Error adding document: \(error)")
    }
    Objective-C
    הערה: המוצר הזה לא זמין ב-watchOS ובמטרות של קליפים של אפליקציות.
    // Add a second document with a generated ID.
    __block FIRDocumentReference *ref =
        [[self.db collectionWithPath:@"users"] addDocumentWithData:@{
          @"first": @"Alan",
          @"middle": @"Mathison",
          @"last": @"Turing",
          @"born": @1912
        } completion:^(NSError * _Nullable error) {
          if (error != nil) {
            NSLog(@"Error adding document: %@", error);
          } else {
            NSLog(@"Document added with ID: %@", ref.documentID);
          }
        }];

    Kotlin

    // Create a new user with a first, middle, and last name
    val user = hashMapOf(
        "first" to "Alan",
        "middle" to "Mathison",
        "last" to "Turing",
        "born" to 1912,
    )
    
    // Add a new document with a generated ID
    db.collection("users")
        .add(user)
        .addOnSuccessListener { documentReference ->
            Log.d(TAG, "DocumentSnapshot added with ID: ${documentReference.id}")
        }
        .addOnFailureListener { e ->
            Log.w(TAG, "Error adding document", e)
        }

    Java

    // Create a new user with a first, middle, and last name
    Map<String, Object> user = new HashMap<>();
    user.put("first", "Alan");
    user.put("middle", "Mathison");
    user.put("last", "Turing");
    user.put("born", 1912);
    
    // Add a new document with a generated ID
    db.collection("users")
            .add(user)
            .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                @Override
                public void onSuccess(DocumentReference documentReference) {
                    Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId());
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.w(TAG, "Error adding document", e);
                }
            });

    Dart

    // Create a new user with a first and last name
    final user = <String, dynamic>{
      "first": "Alan",
      "middle": "Mathison",
      "last": "Turing",
      "born": 1912
    };
    
    // Add a new document with a generated ID
    db.collection("users").add(user).then((DocumentReference doc) =>
        print('DocumentSnapshot added with ID: ${doc.id}'));
    Java
    DocumentReference docRef = db.collection("users").document("aturing");
    // Add document data with an additional field ("middle")
    Map<String, Object> data = new HashMap<>();
    data.put("first", "Alan");
    data.put("middle", "Mathison");
    data.put("last", "Turing");
    data.put("born", 1912);
    
    ApiFuture<WriteResult> result = docRef.set(data);
    System.out.println("Update time : " + result.get().getUpdateTime());
    Python
    doc_ref = db.collection("users").document("aturing")
    doc_ref.set({"first": "Alan", "middle": "Mathison", "last": "Turing", "born": 1912})

    Python

    doc_ref = db.collection("users").document("aturing")
    await doc_ref.set(
        {"first": "Alan", "middle": "Mathison", "last": "Turing", "born": 1912}
    )
    C++‎
    db->Collection("users")
        .Add({{"first", FieldValue::String("Alan")},
              {"middle", FieldValue::String("Mathison")},
              {"last", FieldValue::String("Turing")},
              {"born", FieldValue::Integer(1912)}})
        .OnCompletion([](const Future<DocumentReference>& future) {
          if (future.error() == Error::kErrorOk) {
            std::cout << "DocumentSnapshot added with ID: "
                      << future.result()->id() << std::endl;
          } else {
            std::cout << "Error adding document: " << future.error_message()
                      << std::endl;
          }
        });
    Node.js
    const aTuringRef = db.collection('users').doc('aturing');
    
    await aTuringRef.set({
      'first': 'Alan',
      'middle': 'Mathison',
      'last': 'Turing',
      'born': 1912
    });
    Go
    _, _, err = client.Collection("users").Add(ctx, map[string]interface{}{
    	"first":  "Alan",
    	"middle": "Mathison",
    	"last":   "Turing",
    	"born":   1912,
    })
    if err != nil {
    	log.Fatalf("Failed adding aturing: %v", err)
    }
    PHP

    PHP

    מידע נוסף על התקנה ויצירה של לקוח Cloud Firestore זמין במאמר ספריות לקוח של Cloud Firestore.

    $docRef = $db->collection('samples/php/users')->document('aturing');
    $docRef->set([
        'first' => 'Alan',
        'middle' => 'Mathison',
        'last' => 'Turing',
        'born' => 1912
    ]);
    printf('Added data to the aturing document in the users collection.' . PHP_EOL);
    Unity
    DocumentReference docRef = db.Collection("users").Document("aturing");
    Dictionary<string, object> user = new Dictionary<string, object>
    {
    	{ "First", "Alan" },
    	{ "Middle", "Mathison" },
    	{ "Last", "Turing" },
    	{ "Born", 1912 }
    };
    docRef.SetAsync(user).ContinueWithOnMainThread(task => {
    	Debug.Log("Added data to the aturing document in the users collection.");
    });
    C#‎
    DocumentReference docRef = db.Collection("users").Document("aturing");
    Dictionary<string, object> user = new Dictionary<string, object>
    {
        { "First", "Alan" },
        { "Middle", "Mathison" },
        { "Last", "Turing" },
        { "Born", 1912 }
    };
    await docRef.SetAsync(user);
    Ruby
    doc_ref = firestore.doc "#{collection_path}/aturing"
    
    doc_ref.set(
      {
        first:  "Alan",
        middle: "Mathison",
        last:   "Turing",
        born:   1912
      }
    )
    
    puts "Added data to the aturing document in the users collection."

    קריאת נתונים

    אפשר להשתמש בכלי להצגת נתונים במסוף Firebase כדי לוודא במהירות שהוספתם נתונים ל-Cloud Firestore.

    אפשר גם להשתמש בשיטת get כדי לאחזר את כל האוסף.

    Web

    import { collection, getDocs } from "firebase/firestore"; 
    
    const querySnapshot = await getDocs(collection(db, "users"));
    querySnapshot.forEach((doc) => {
      console.log(`${doc.id} => ${doc.data()}`);
    });

    Web

    db.collection("users").get().then((querySnapshot) => {
        querySnapshot.forEach((doc) => {
            console.log(`${doc.id} => ${doc.data()}`);
        });
    });
    Swift
    הערה: המוצר הזה לא זמין ב-watchOS ובמטרות של קליפים של אפליקציות.
    do {
      let snapshot = try await db.collection("users").getDocuments()
      for document in snapshot.documents {
        print("\(document.documentID) => \(document.data())")
      }
    } catch {
      print("Error getting documents: \(error)")
    }
    Objective-C
    הערה: המוצר הזה לא זמין ב-watchOS ובמטרות של קליפים של אפליקציות.
    [[self.db collectionWithPath:@"users"]
        getDocumentsWithCompletion:^(FIRQuerySnapshot * _Nullable snapshot,
                                     NSError * _Nullable error) {
          if (error != nil) {
            NSLog(@"Error getting documents: %@", error);
          } else {
            for (FIRDocumentSnapshot *document in snapshot.documents) {
              NSLog(@"%@ => %@", document.documentID, document.data);
            }
          }
        }];

    Kotlin

    db.collection("users")
        .get()
        .addOnSuccessListener { result ->
            for (document in result) {
                Log.d(TAG, "${document.id} => ${document.data}")
            }
        }
        .addOnFailureListener { exception ->
            Log.w(TAG, "Error getting documents.", exception)
        }

    Java

    db.collection("users")
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (task.isSuccessful()) {
                        for (QueryDocumentSnapshot document : task.getResult()) {
                            Log.d(TAG, document.getId() + " => " + document.getData());
                        }
                    } else {
                        Log.w(TAG, "Error getting documents.", task.getException());
                    }
                }
            });

    Dart

    await db.collection("users").get().then((event) {
      for (var doc in event.docs) {
        print("${doc.id} => ${doc.data()}");
      }
    });
    Java
    // asynchronously retrieve all users
    ApiFuture<QuerySnapshot> query = db.collection("users").get();
    // ...
    // query.get() blocks on response
    QuerySnapshot querySnapshot = query.get();
    List<QueryDocumentSnapshot> documents = querySnapshot.getDocuments();
    for (QueryDocumentSnapshot document : documents) {
      System.out.println("User: " + document.getId());
      System.out.println("First: " + document.getString("first"));
      if (document.contains("middle")) {
        System.out.println("Middle: " + document.getString("middle"));
      }
      System.out.println("Last: " + document.getString("last"));
      System.out.println("Born: " + document.getLong("born"));
    }
    Python
    users_ref = db.collection("users")
    docs = users_ref.stream()
    
    for doc in docs:
        print(f"{doc.id} => {doc.to_dict()}")

    Python

    users_ref = db.collection("users")
    docs = users_ref.stream()
    
    async for doc in docs:
        print(f"{doc.id} => {doc.to_dict()}")
    C++‎
    Future<QuerySnapshot> users = db->Collection("users").Get();
    users.OnCompletion([](const Future<QuerySnapshot>& future) {
      if (future.error() == Error::kErrorOk) {
        for (const DocumentSnapshot& document : future.result()->documents()) {
          std::cout << document << std::endl;
        }
      } else {
        std::cout << "Error getting documents: " << future.error_message()
                  << std::endl;
      }
    });
    Node.js
    const snapshot = await db.collection('users').get();
    snapshot.forEach((doc) => {
      console.log(doc.id, '=>', doc.data());
    });
    Go
    iter := client.Collection("users").Documents(ctx)
    for {
    	doc, err := iter.Next()
    	if err == iterator.Done {
    		break
    	}
    	if err != nil {
    		log.Fatalf("Failed to iterate: %v", err)
    	}
    	fmt.Println(doc.Data())
    }
    PHP

    PHP

    מידע נוסף על התקנה ויצירה של לקוח Cloud Firestore זמין במאמר ספריות לקוח של Cloud Firestore.

    $usersRef = $db->collection('samples/php/users');
    $snapshot = $usersRef->documents();
    foreach ($snapshot as $user) {
        printf('User: %s' . PHP_EOL, $user->id());
        printf('First: %s' . PHP_EOL, $user['first']);
        if (!empty($user['middle'])) {
            printf('Middle: %s' . PHP_EOL, $user['middle']);
        }
        printf('Last: %s' . PHP_EOL, $user['last']);
        printf('Born: %d' . PHP_EOL, $user['born']);
        printf(PHP_EOL);
    }
    printf('Retrieved and printed out all documents from the users collection.' . PHP_EOL);
    Unity
    CollectionReference usersRef = db.Collection("users");
    usersRef.GetSnapshotAsync().ContinueWithOnMainThread(task =>
    {
      QuerySnapshot snapshot = task.Result;
      foreach (DocumentSnapshot document in snapshot.Documents)
      {
        Debug.Log(String.Format("User: {0}", document.Id));
        Dictionary<string, object> documentDictionary = document.ToDictionary();
        Debug.Log(String.Format("First: {0}", documentDictionary["First"]));
        if (documentDictionary.ContainsKey("Middle"))
        {
          Debug.Log(String.Format("Middle: {0}", documentDictionary["Middle"]));
        }
    
        Debug.Log(String.Format("Last: {0}", documentDictionary["Last"]));
        Debug.Log(String.Format("Born: {0}", documentDictionary["Born"]));
      }
    
      Debug.Log("Read all data from the users collection.");
    });
    C#‎
    CollectionReference usersRef = db.Collection("users");
    QuerySnapshot snapshot = await usersRef.GetSnapshotAsync();
    foreach (DocumentSnapshot document in snapshot.Documents)
    {
        Console.WriteLine("User: {0}", document.Id);
        Dictionary<string, object> documentDictionary = document.ToDictionary();
        Console.WriteLine("First: {0}", documentDictionary["First"]);
        if (documentDictionary.ContainsKey("Middle"))
        {
            Console.WriteLine("Middle: {0}", documentDictionary["Middle"]);
        }
        Console.WriteLine("Last: {0}", documentDictionary["Last"]);
        Console.WriteLine("Born: {0}", documentDictionary["Born"]);
        Console.WriteLine();
    }
    Ruby
    users_ref = firestore.col collection_path
    users_ref.get do |user|
      puts "#{user.document_id} data: #{user.data}."
    end

    אבטחת הנתונים

    אם אתם משתמשים ב-SDK של פלטפורמות האינטרנט, Android או Apple, אתם יכולים להשתמש באימות ב-Firebase וב-Cloud Firestore Security Rules כדי לאבטח את הנתונים ב-Cloud Firestore.

    ריכזנו כאן כמה קבוצות כללים בסיסיות שתוכלו להשתמש בהן כדי להתחיל. אפשר לשנות את כללי האבטחה בכרטיסייה Rules במסוף.

    נדרש אימות

    // Allow read/write access to a document keyed by the user's UID
    service cloud.firestore {
      match /databases/{database}/documents {
        match /users/{uid} {
          allow read, write: if request.auth != null && request.auth.uid == uid;
        }
      }
    }
    

    מצב נעילה

    // Deny read/write access to all users under any conditions
    service cloud.firestore {
      match /databases/{database}/documents {
        match /{document=**} {
          allow read, write: if false;
        }
      }
    }
    

    לפני שפורסים את אפליקציית האינטרנט, Android או iOS בסביבת הייצור, צריך גם לבצע פעולות כדי לוודא שרק לקוחות האפליקציה יכולים לגשת לנתוני Cloud Firestore. מידע נוסף זמין בתיעוד בנושא App Check.

    אם אתם משתמשים באחת מערכות ה-SDK של השרת, אתם יכולים להשתמש בניהול זהויות והרשאות גישה (IAM) כדי לאבטח את הנתונים ב-Cloud Firestore.

    צפייה בסרטון הדרכה

    כדי לקבל הנחיות מפורטות לתחילת העבודה עם Cloud Firestoreספריות לקוח לנייד, אפשר לצפות באחד מסרטוני ההדרכה הבאים:

    אינטרנט
    ‫iOS+
    Android

    סרטונים נוספים זמינים בערוץ YouTube של Firebase.

    השלבים הבאים

    כדי להרחיב את הידע, כדאי לעיין בנושאים הבאים: