Cloud Firestore'u kullanmaya başlama

Bu hızlı başlangıç kılavuzunda Cloud Firestore nasıl ayarlanacağı, veri nasıl ekleneceği ve eklediğiniz verilerin Firebase konsolunda nasıl görüntüleneceği açıklanmaktadır.

Cloud Firestore veritabanı oluşturma

  1. Henüz yapmadıysanız Firebase projesi oluşturun: Firebase konsolunda Proje ekle'yi tıklayın, ardından Firebase projesi oluşturmak veya Firebase hizmetlerini mevcut bir Google Cloud projesine eklemek için ekrandaki talimatları uygulayın.

  2. Projenizi Firebase konsolunda açın. Sol panelde Oluştur'u genişletin ve Firestore veritabanı'nı seçin.

  3. Create database'i (Veritabanı oluştur) tıklayın.

  4. Veritabanınız için bir konum seçin.

    Konum seçemiyorsanız projenizin "varsayılan Google Cloud kaynaklarının konumu" zaten ayarlanmıştır. Projenizin bazı kaynakları (ör. varsayılan Cloud Firestore örneği) ortak bir konum bağımlılığına sahiptir ve konumları proje oluşturma sırasında veya bu konum bağımlılığını paylaşan başka bir hizmet kurulurken ayarlanabilir.

  5. Cloud Firestore Security Rules için bir başlangıç modu seçin:

    Test modu

    Mobil ve web istemci kitaplıklarını kullanmaya başlamak için uygundur ancak herkesin verilerinizi okumasına ve üzerine yazmasına izin verir. Testten sonra Verilerinizi güvene alın bölümünü incelemeyi unutmayın.

    Web, Apple platformları veya Android SDK'sını kullanmaya başlamak için test modunu seçin.

    Kilitli mod

    Mobil ve web istemcilerinden gelen tüm okuma ve yazma işlemlerini reddeder. Kimliği doğrulanmış uygulama sunucularınız (C#, Go, Java, Node.js, PHP, Python veya Ruby) veritabanınıza erişmeye devam edebilir.

    C#, Go, Java, Node.js, PHP, Python veya Ruby sunucu istemci kitaplığını kullanmaya başlamak için kilitli modu seçin.

    İlk Cloud Firestore Security Rules kümeniz varsayılan Cloud Firestore veritabanınıza uygulanır. Projeniz için birden fazla veritabanı oluşturursanız her veritabanı için Cloud Firestore Security Rules dağıtabilirsiniz.

  6. Oluştur'u tıklayın.

Cloud Firestore'yı etkinleştirdiğinizde Cloud API Yöneticisi'nde de API etkinleştirilir.

Geliştirme ortamınızı kurma

Gerekli bağımlılıkları ve istemci kitaplıklarını uygulamanıza ekleyin.

Web

  1. Firebase'i web uygulamanıza ekleme talimatlarını uygulayın.
  2. Cloud Firestore SDK'sı, npm paketi olarak kullanılabilir.
    npm install firebase@11.10.0 --save
    Hem Firebase'i hem de Cloud Firestore'ı içe aktarmanız gerekir.
    import { initializeApp } from "firebase/app";
    import { getFirestore } from "firebase/firestore";

Web

  1. Firebase'i web uygulamanıza ekleme talimatlarını uygulayın.
  2. Firebase ve Cloud Firestore kitaplıklarını uygulamanıza ekleyin:
    <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'sı npm paketi olarak da kullanılabilir.
    npm install firebase@11.10.0 --save
    Hem Firebase'i hem de Cloud Firestore'ı manuel olarak istemeniz gerekir.
    import firebase from "firebase/compat/app";
    // Required for side-effects
    import "firebase/firestore";
iOS+

Firebase'i Apple uygulamanıza ekleme talimatlarını uygulayın.

Firebase bağımlılarını yükleyip yönetmek için Swift Package Manager'ı kullanın.

  1. Xcode'da, uygulama projeniz açıkken File > Swift Packages > Add Package Dependency (Dosya > Swift Paketleri > Paket Bağımlısı Ekle) seçeneğine gidin.
  2. İstendiğinde Firebase Apple platformları SDK deposunu ekleyin:
  3.   https://github.com/firebase/firebase-ios-sdk
      
  4. Firestore kitaplığını seçin.
  5. İşlem tamamlandığında Xcode otomatik olarak arka planda bağımlılarınızı çözümlemeye ve indirmeye başlar.
Android
  1. Firebase'i Android uygulamanıza ekleme talimatlarını uygulayın.
  2. Firebase Android BoM'u kullanarak Android için Cloud Firestore kitaplığına olan bağımlılığı modülünüzün (uygulama düzeyinde) Gradle dosyasında (genellikle app/build.gradle.kts veya app/build.gradle) tanımlayın.
    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 kullanıldığında uygulamanız Firebase Android kitaplıklarının daima uyumlu sürümlerini kullanır.

    (Alternatif) Firebase kitaplığı bağımlılıklarını olmadan bildirin. BoM

    Firebase BoM kullanmamayı tercih ederseniz her Firebase kitaplık sürümünü bağımlılık satırında belirtmeniz gerekir.

    Uygulamanızda birden fazla Firebase kitaplığı kullanıyorsanız kitaplık sürümlerini yönetmek için BoM kullanmanızı önemle tavsiye ederiz. Bu sayede tüm sürümlerin uyumlu olması sağlanır.

    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'e özgü bir kitaplık modülü mü arıyorsunuz? Ekim 2023 sürümünden itibaren hem Kotlin hem de Java geliştiriciler ana kitaplık modülünü kullanabilir (ayrıntılar için bu girişimle ilgili SSS bölümüne bakın).

Dart

  1. Henüz yapmadıysanız Flutter uygulamanızda Firebase'i yapılandırın ve başlatın.
  2. Eklentiyi yüklemek için Flutter projenizin kökünden aşağıdaki komutu çalıştırın:
    flutter pub add cloud_firestore
  3. İşlem tamamlandıktan sonra Flutter uygulamanızı yeniden oluşturun:
    flutter run
  4. İsteğe bağlı: Önceden derlenmiş çerçeveyi ekleyerek iOS ve macOS derleme sürelerini kısaltın.

    Şu anda iOS için Firestore SDK'sı, Xcode'da oluşturulması 5 dakikadan uzun sürebilen koda bağlıdır. Derleme sürelerini önemli ölçüde azaltmak için Podfile'ınızdaki target 'Runner' do bloğuna bu satırı ekleyerek önceden derlenmiş bir sürümü kullanabilirsiniz:

    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 yerine firebase_core'nin firebase_sdk_version.rb dosyasında belirtilen Firebase iOS SDK'sının sürümünü girin. firebase_core'nın en son sürümünü kullanmıyorsanız bu dosyayı yerel Pub paketi önbelleğinizde (genellikle ~/.pub-cache) bulun.

    Ayrıca, CocoaPods'u 1.9.1 veya daha yeni bir sürüme yükselttiğinizden emin olun:

    gem install cocoapods

    Daha fazla bilgi için GitHub'daki soruna göz atın.

Java
  1. Firebase Admin SDK'sını uygulamanıza ekleyin:
    • Gradle'ı kullanma:
      compile 'com.google.firebase:firebase-admin:1.32.0'
    • Maven'i kullanma:
      <dependency>
        <groupId>com.google.firebase</groupId>
        <artifactId>firebase-admin</artifactId>
        <version>1.32.0</version>
      </dependency>
           
  2. Ortamınızda Cloud Firestore'ı uygun kimlik bilgileriyle başlatmak için aşağıdaki talimatları uygulayın.
Python
  1. Firebase Admin SDK'sını Python uygulamanıza ekleyin:
    pip install --upgrade firebase-admin
  2. Ortamınızda Cloud Firestore'ı uygun kimlik bilgileriyle başlatmak için aşağıdaki talimatları uygulayın.
C++
  1. Firebase'i C++ projenize ekleme talimatlarını uygulayın.
  2. Android için C++ arayüzü.
    • Gradle bağımlılıkları. Modülünüzün (uygulama düzeyinde) Gradle dosyasına (genellikle app/build.gradle) aşağıdakileri ekleyin:
              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
              }
              
    • İkili bağımlılıklar. Benzer şekilde, ikili bağımlılıkları elde etmenin önerilen yolu, CMakeLists.txt dosyanıza aşağıdakileri eklemektir:
              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. Masaüstü entegrasyonunu ayarlamak için Firebase'i C++ projenize ekleme başlıklı makaleye bakın.
Unity
  1. Firebase'i Unity projenize ekleme talimatlarını uygulayın.
  2. Projenizi Android derlemelerini küçültecek şekilde yapılandırmak için Unity arayüzünü kullanın.
  3. Error while merging dex archives mesajını önlemek için derlemeyi küçültmeniz gerekir.

    • Bu seçeneği Player Settings > Android > Publishing Settings > Minify (Oynatıcı Ayarları > Android > Yayınlama Ayarları > Küçült) bölümünde bulabilirsiniz.
    • Seçenekler Unity'nin farklı sürümlerinde farklılık gösterebilir. Bu nedenle, resmi Unity belgelerine ve Firebase Unity Build Debug Guide'a bakın.
    • Küçültme etkinleştirildikten sonra başvurulan yöntemlerin sayısı hâlâ sınırı aşıyorsa multidex seçeneğini etkinleştirebilirsiniz:
      • mainTemplate.gradle Player Settings (Oynatıcı Ayarları) bölümünde Custom Gradle Template (Özel Gradle Şablonu) etkinse
      • veya dışa aktarılan projeyi oluşturmak için Android Studio'yu kullanıyorsanız modül düzeyindeki build.gradle dosyası.
Node.js
  1. Firebase Admin SDK'sını uygulamanıza ekleyin:
    npm install firebase-admin --save
  2. Ortamınızda Cloud Firestore'ı uygun kimlik bilgileriyle başlatmak için aşağıdaki talimatları uygulayın.
Go
  1. Firebase Admin SDK'sını Go uygulamanıza ekleyin:
    go get firebase.google.com/go
  2. Ortamınızda Cloud Firestore'ı uygun kimlik bilgileriyle başlatmak için aşağıdaki talimatları uygulayın.
PHP
  1. Cloud Firestore sunucu istemci kitaplıkları (Java, Node.js, Python, Go, PHP, C# ve Ruby) kimlik doğrulama için Google Uygulaması Varsayılan Kimlik Bilgilerini kullanır.
    • Geliştirme ortamınızdan kimlik doğrulamak için GOOGLE_APPLICATION_CREDENTIALS ortam değişkenini bir JSON hizmet hesabı anahtar dosyasına yönlendirecek şekilde ayarlayın. API Konsolu Kimlik Bilgileri sayfasında anahtar dosyası oluşturabilirsiniz.
      export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
    • Uygulamanızı Cloud Firestore için kullandığınız projeyi kullanarak App Engine veya Compute Engine'de çalıştırıyorsanız üretim ortamınızda kimlik doğrulama yapmanız gerekmez. Aksi takdirde bir hizmet hesabı oluşturun.
  2. İstemci kitaplığını kullanmak için PHP'de gRPC uzantısını yükleyip etkinleştirin.
  3. Uygulamanıza Cloud Firestore PHP kitaplığını ekleyin:
    composer require google/cloud-firestore
C#
  1. Cloud Firestore sunucu istemci kitaplıkları (Java, Node.js, Python, Go, PHP, C# ve Ruby) kimlik doğrulama için Google Uygulaması Varsayılan Kimlik Bilgilerini kullanır.
    • Geliştirme ortamınızdan kimlik doğrulamak için GOOGLE_APPLICATION_CREDENTIALS ortam değişkenini bir JSON hizmet hesabı anahtar dosyasına yönlendirecek şekilde ayarlayın. API Konsolu Kimlik Bilgileri sayfasında anahtar dosyası oluşturabilirsiniz.
      export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
    • Uygulamanızı Cloud Firestore için kullandığınız projeyi kullanarak App Engine veya Compute Engine'de çalıştırıyorsanız üretim ortamınızda kimlik doğrulama yapmanız gerekmez. Aksi takdirde bir hizmet hesabı oluşturun.
  2. .csproj dosyanızda uygulamanıza Cloud Firestore C# kitaplığını ekleyin:
    <ItemGroup>
      <PackageReference Include="Google.Cloud.Firestore" Version="1.1.0-beta01" />
    </ItemGroup>
  3. Program.cs dosyanıza aşağıdakileri ekleyin:
    using Google.Cloud.Firestore;
Ruby
  1. Cloud Firestore sunucu istemci kitaplıkları (Java, Node.js, Python, Go, PHP, C# ve Ruby) kimlik doğrulama için Google Uygulaması Varsayılan Kimlik Bilgilerini kullanır.
    • Geliştirme ortamınızdan kimlik doğrulamak için GOOGLE_APPLICATION_CREDENTIALS ortam değişkenini bir JSON hizmet hesabı anahtar dosyasına yönlendirecek şekilde ayarlayın. API Konsolu Kimlik Bilgileri sayfasında anahtar dosyası oluşturabilirsiniz.
      export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
    • Uygulamanızı Cloud Firestore için kullandığınız projeyi kullanarak App Engine veya Compute Engine'de çalıştırıyorsanız üretim ortamınızda kimlik doğrulama yapmanız gerekmez. Aksi takdirde bir hizmet hesabı oluşturun.
  2. Cloud Firestore Ruby kitaplığını Gemfile bölümünde uygulamanıza ekleyin:
    gem "google-cloud-firestore"
  3. Gemfile cihazınızdaki bağımlılıkları yüklemek için:
    bundle install

(İsteğe bağlı) Firebase Local Emulator Suite ile prototip oluşturma ve test etme

Mobil geliştiriciler için, uygulamanızın Cloud Firestore ile nasıl okuma ve yazma işlemi yaptığını anlatmadan önce Cloud Firestore işlevinin prototipini oluşturmak ve test etmek için kullanabileceğiniz bir dizi aracı tanıtalım: Firebase Local Emulator Suite. Farklı veri modellerini deniyorsanız, güvenlik kurallarınızı optimize ediyorsanız veya arka uçla etkileşim kurmanın en uygun maliyetli yolunu bulmaya çalışıyorsanız canlı hizmetleri dağıtmadan yerel olarak çalışabilmek harika bir fikir olabilir.

Cloud Firestore emülatörü, Local Emulator Suite'nin bir parçasıdır. Bu araç, uygulamanızın emüle edilmiş veritabanı içeriğiniz ve yapılandırmanızla, ayrıca isteğe bağlı olarak emüle edilmiş proje kaynaklarınızla (işlevler, diğer veritabanları ve güvenlik kuralları) etkileşim kurmasını sağlar.

Cloud Firestore emülatörünü kullanmak için yalnızca birkaç adım gerekir:

  1. Emülatöre bağlanmak için uygulamanızın test yapılandırmasına bir kod satırı ekleyin.
  2. Yerel proje dizininizin kökünden firebase emulators:start komutunu çalıştırın.
  3. Her zamanki gibi bir Cloud Firestore platform SDK'sı kullanarak uygulamanızın prototip kodundan çağrı yapma.

Cloud Firestore ve Cloud Functions ile ilgili ayrıntılı birrehber mevcuttur. Ayrıca Local Emulator Suite giriş bölümüne de göz atmanız gerekir.

Cloud Firestore başlatılıyor

Cloud Firestore örneğini başlatın:

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 yerine web uygulamanızın firebaseConfig değerini girin.

Cihaz bağlantısını kaybettiğinde verilerin kalıcı olması için Çevrimdışı Verileri Etkinleştirme dokümanına bakın.

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 yerine web uygulamanızın firebaseConfig değerini girin.

Cihaz bağlantısını kaybettiğinde verilerin kalıcı olması için Çevrimdışı Verileri Etkinleştirme dokümanına bakın.

Swift
Not: Bu ürün, watchOS ve App Clip hedeflerinde kullanılamaz.
import FirebaseCore
import FirebaseFirestore
FirebaseApp.configure()

let db = Firestore.firestore()
Objective-C
Not: Bu ürün, watchOS ve App Clip hedeflerinde kullanılamaz.
@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, ortamınıza bağlı olarak farklı şekillerde başlatılır. En yaygın yöntemler aşağıda verilmiştir. Tam referans için Yönetici SDK'sını başlatma başlıklı makaleyi inceleyin.
  • Google Cloud tarihinde ilk kullanıma hazırlama
    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();
  • Kendi sunucunuzda başlatma

    Firebase Admin SDK'yı kendi sunucunuzda kullanmak için hizmet hesabı kullanın.

    Google Cloud Console'da IAM ve yönetici > Hizmet hesapları'na gidin. Yeni bir özel anahtar oluşturun ve JSON dosyasını kaydedin. Ardından, SDK'yı başlatmak için dosyayı kullanın:

    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, ortamınıza bağlı olarak farklı şekillerde başlatılır. En yaygın yöntemler aşağıda verilmiştir. Tam referans için Yönetici SDK'sını başlatma başlıklı makaleyi inceleyin.
  • Google Cloud tarihinde ilk kullanıma hazırlama
    import firebase_admin
    from firebase_admin import firestore
    
    # Application Default credentials are automatically created.
    app = firebase_admin.initialize_app()
    db = firestore.client()

    SDK'yı başlatmak için mevcut bir varsayılan uygulama kimlik bilgisi de kullanılabilir.

    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()
  • Kendi sunucunuzda başlatma

    Firebase Admin SDK'yı kendi sunucunuzda kullanmak için hizmet hesabı kullanın.

    Google Cloud Console'da IAM ve yönetici > Hizmet hesapları'na gidin. Yeni bir özel anahtar oluşturun ve JSON dosyasını kaydedin. Ardından, SDK'yı başlatmak için dosyayı kullanın:

    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, ortamınıza bağlı olarak farklı şekillerde başlatılır. En yaygın yöntemler aşağıda verilmiştir. Tam referans için Yönetici SDK'sını başlatma başlıklı makaleyi inceleyin.
  • Google Cloud tarihinde ilk kullanıma hazırlama
    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'yı başlatmak için mevcut bir varsayılan uygulama kimlik bilgisi de kullanılabilir.

    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()
  • Kendi sunucunuzda başlatma

    Firebase Admin SDK'yı kendi sunucunuzda kullanmak için hizmet hesabı kullanın.

    Google Cloud Console'da IAM ve yönetici > Hizmet hesapları'na gidin. Yeni bir özel anahtar oluşturun ve JSON dosyasını kaydedin. Ardından, SDK'yı başlatmak için dosyayı kullanın:

    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, ortamınıza bağlı olarak farklı şekillerde başlatılır. En yaygın yöntemler aşağıda verilmiştir. Tam referans için Yönetici SDK'sını başlatma başlıklı makaleyi inceleyin.
    • Cloud Functions tarihinde ilk kullanıma hazırlama
      const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
      const { getFirestore, Timestamp, FieldValue, Filter } = require('firebase-admin/firestore');
      initializeApp();
      
      const db = getFirestore();
      
    • Google Cloud tarihinde ilk kullanıma hazırlama
      const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
      const { getFirestore, Timestamp, FieldValue, Filter } = require('firebase-admin/firestore');
      initializeApp({
        credential: applicationDefault()
      });
      
      const db = getFirestore();
    • Kendi sunucunuzda başlatma

      Firebase Admin SDK'yı kendi sunucunuzda (veya başka bir Node.js ortamında) kullanmak için hizmet hesabı kullanın. Google Cloud Console'da IAM ve yönetici > Hizmet hesapları'na gidin. Yeni bir özel anahtar oluşturun ve JSON dosyasını kaydedin. Ardından, SDK'yı başlatmak için dosyayı kullanın:

      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, ortamınıza bağlı olarak farklı şekillerde başlatılır. En yaygın yöntemler aşağıda verilmiştir. Tam referans için Yönetici SDK'sını başlatma başlıklı makaleyi inceleyin.
  • Google Cloud tarihinde ilk kullanıma hazırlama
    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()
  • Kendi sunucunuzda başlatma

    Firebase Admin SDK'yı kendi sunucunuzda kullanmak için hizmet hesabı kullanın.

    Google Cloud Console'da IAM ve yönetici > Hizmet hesapları'na gidin. Yeni bir özel anahtar oluşturun ve JSON dosyasını kaydedin. Ardından, SDK'yı başlatmak için dosyayı kullanın:

    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 istemcisini yükleme ve oluşturma hakkında daha fazla bilgi için Cloud Firestore İstemci Kitaplıkları başlıklı makaleyi inceleyin.

    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 istemcisini yükleme ve oluşturma hakkında daha fazla bilgi için Cloud Firestore İstemci Kitaplıkları başlıklı makaleyi inceleyin.

    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."

    Veri ekle

    Cloud Firestore, verileri Koleksiyonlarda depolanan Belgeler'de saklar. Cloud Firestore, dokümana ilk kez veri eklediğinizde koleksiyonları ve dokümanları örtülü olarak oluşturur. Koleksiyon veya doküman oluşturmanız gerekmez.

    Aşağıdaki örnek kodu kullanarak yeni bir koleksiyon ve doküman oluşturun.

    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
    Not: Bu ürün, watchOS ve App Clip hedeflerinde kullanılamaz.
    // 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
    Not: Bu ürün, watchOS ve App Clip hedeflerinde kullanılamaz.
    // 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 istemcisini yükleme ve oluşturma hakkında daha fazla bilgi için Cloud Firestore İstemci Kitaplıkları başlıklı makaleyi inceleyin.

    $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."

    Şimdi users koleksiyonuna başka bir belge ekleyin. Bu belgede, ilk belgede görünmeyen bir anahtar/değer çifti (ikinci ad) olduğunu unutmayın. Koleksiyondaki belgeler farklı bilgi kümeleri içerebilir.

    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
    Not: Bu ürün, watchOS ve App Clip hedeflerinde kullanılamaz.
    // 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
    Not: Bu ürün, watchOS ve App Clip hedeflerinde kullanılamaz.
    // 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 istemcisini yükleme ve oluşturma hakkında daha fazla bilgi için Cloud Firestore İstemci Kitaplıkları başlıklı makaleyi inceleyin.

    $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."

    Verileri okuma

    Cloud Firestore'ye veri eklediğinizi hızlıca doğrulamak için Firebase konsolundaki veri görüntüleyiciyi kullanın.

    Koleksiyonun tamamını almak için "get" yöntemini de kullanabilirsiniz.

    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
    Not: Bu ürün, watchOS ve App Clip hedeflerinde kullanılamaz.
    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
    Not: Bu ürün, watchOS ve App Clip hedeflerinde kullanılamaz.
    [[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 istemcisini yükleme ve oluşturma hakkında daha fazla bilgi için Cloud Firestore İstemci Kitaplıkları başlıklı makaleyi inceleyin.

    $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

    Verilerinizi güvence altına alma

    Web, Android veya Apple platformları SDK'sını kullanıyorsanız Firebase Authentication ve Cloud Firestore Security Rules kullanarak verilerinizi Cloud Firestore içinde güvenceye alın.

    Başlamak için kullanabileceğiniz bazı temel kural kümelerini aşağıda bulabilirsiniz. Güvenlik kurallarınızı konsolun Kurallar sekmesinde değiştirebilirsiniz.

    Yetkilendirme gerekli

    // 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;
        }
      }
    }
    

    Kilitli mod

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

    Web, Android veya iOS uygulamanızı üretime dağıtmadan önce, yalnızca uygulama istemcilerinizin Cloud Firestore verilerinize erişebildiğinden emin olmak için de gerekli adımları atın. App Check belgelerine bakın.

    Sunucu SDK'larından birini kullanıyorsanız Cloud Firestore'deki verilerinizi güvenceye almak için Kimlik ve Erişim Yönetimi (IAM)'ni kullanın.

    Eğitim videosu izleyin

    Cloud Firestore Mobil istemci kitaplıklarını kullanmaya başlama hakkında ayrıntılı bilgi için aşağıdaki video eğitimlerinden birini izleyin:

    Web
    iOS+
    Android

    Daha fazla videoyu Firebase YouTube kanalında bulabilirsiniz.

    Sonraki adımlar

    Aşağıdaki konularla bilginizi derinleştirin:

    • Codelabs: Cloud Firestore'ı gerçek bir uygulamada kullanmayı öğrenmek için Android, iOS veya web ile ilgili codelab'i takip edin.
    • Veri modeli: Hiyerarşik veriler ve alt koleksiyonlar dahil olmak üzere verilerin Cloud Firestore içinde nasıl yapılandırıldığı hakkında daha fazla bilgi edinin.
    • Veri ekleme: Cloud Firestore'de veri oluşturma ve güncelleme hakkında daha fazla bilgi edinin.
    • Veri alma: Verilerin nasıl alınacağı hakkında daha fazla bilgi edinin.
    • Basit ve bileşik sorgular gerçekleştirme: Basit ve bileşik sorguları nasıl çalıştıracağınızı öğrenin.
    • Sorguları sıralama ve sınırlama Sorgularınız tarafından döndürülen verileri nasıl sıralayacağınızı ve sınırlayacağınızı öğrenin.