Bắt đầu sử dụng Cloud Firestore

Hướng dẫn nhanh này cho bạn biết cách thiết lập Cloud Firestore, thêm dữ liệu, sau đó xem dữ liệu bạn vừa thêm trong bảng điều khiển của Firebase.

Tạo cơ sở dữ liệu Cloud Firestore

  1. Nếu chưa có, bạn cần tạo một dự án Firebase: Trong bảng điều khiển Firebase, hãy nhấp vào Thêm dự án, sau đó làm theo hướng dẫn trên màn hình để tạo một dự án Firebase hoặc thêm các dịch vụ của Firebase vào một dự án Google Cloud hiện có.

  2. Mở dự án của bạn trong bảng điều khiển Firebase. Trong bảng điều khiển bên trái, hãy mở rộng Build (Xây dựng) rồi chọn Cơ sở dữ liệu Firestore.

  3. Nhấp vào Tạo cơ sở dữ liệu.

  4. Chọn một vị trí cho cơ sở dữ liệu của bạn.

    Nếu không chọn được vị trí, tức là bạn đã đặt "vị trí cho tài nguyên Google Cloud mặc định" của dự án. Một số tài nguyên của dự án (chẳng hạn như thực thể Cloud Firestore mặc định) dùng chung một phần phụ thuộc vị trí và vị trí của các tài nguyên này có thể được đặt trong quá trình tạo dự án hoặc khi thiết lập một dịch vụ khác dùng chung phần phụ thuộc vị trí này.

  5. Chọn chế độ khởi động cho Cloud Firestore Security Rules:

    Chế độ kiểm thử

    Phù hợp để bắt đầu với các thư viện ứng dụng di động và ứng dụng web, nhưng cho phép mọi người đọc và ghi đè dữ liệu của bạn. Sau khi kiểm thử, hãy nhớ xem xét phần Bảo mật dữ liệu của bạn.

    Để bắt đầu với SDK web, SDK cho các nền tảng của Apple hoặc SDK Android, hãy chọn chế độ kiểm thử.

    Chế độ khoá

    Từ chối mọi hoạt động đọc và ghi từ ứng dụng di động và ứng dụng web. Các máy chủ ứng dụng đã xác thực (C#, Go, Java, Node.js, PHP, Python hoặc Ruby) vẫn có thể truy cập vào cơ sở dữ liệu của bạn.

    Để bắt đầu sử dụng thư viện ứng dụng máy chủ C#, Go, Java, Node.js, PHP, Python hoặc Ruby, hãy chọn chế độ khoá.

    Nhóm Cloud Firestore Security Rules ban đầu sẽ áp dụng cho cơ sở dữ liệu Cloud Firestore mặc định của bạn. Nếu tạo nhiều cơ sở dữ liệu cho dự án, bạn có thể triển khai Cloud Firestore Security Rules cho từng cơ sở dữ liệu.

  6. Nhấp vào Tạo.

Khi bạn bật Cloud Firestore, API này cũng sẽ được bật trong Trình quản lý API trên đám mây.

Thiết lập môi trường phát triển

Thêm các phần phụ thuộc và thư viện ứng dụng bắt buộc vào ứng dụng của bạn.

Web

  1. Làm theo hướng dẫn để thêm Firebase vào ứng dụng web.
  2. SDK Cloud Firestore có sẵn dưới dạng một gói npm.
    npm install firebase@12.0.0 --save
    Bạn cần nhập cả Firebase và Cloud Firestore.
    import { initializeApp } from "firebase/app";
    import { getFirestore } from "firebase/firestore";

Web

  1. Làm theo hướng dẫn để thêm Firebase vào ứng dụng web.
  2. Thêm thư viện Firebase và Cloud Firestore vào ứng dụng của bạn:
    <script src="https://www.gstatic.com/firebasejs/12.0.0/firebase-app-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/12.0.0/firebase-firestore-compat.js"></script>
    SDK Cloud Firestore cũng có sẵn dưới dạng một gói npm.
    npm install firebase@12.0.0 --save
    Bạn cần phải yêu cầu cả Firebase và Cloud Firestore theo cách thủ công.
    import firebase from "firebase/compat/app";
    // Required for side-effects
    import "firebase/firestore";
iOS+

Làm theo hướng dẫn để thêm Firebase vào ứng dụng Apple.

Sử dụng Swift Package Manager để cài đặt và quản lý các phần phụ thuộc của Firebase.

  1. Trong Xcode, khi dự án ứng dụng của bạn đang mở, hãy chuyển đến File (Tệp) > Swift Packages (Gói Swift) > Add Package Dependency (Thêm phần phụ thuộc của gói).
  2. Khi được nhắc, hãy thêm kho lưu trữ SDK Firebase cho các nền tảng của Apple:
  3.   https://github.com/firebase/firebase-ios-sdk
      
  4. Chọn thư viện Firestore.
  5. Khi hoàn tất, Xcode sẽ tự động bắt đầu phân giải và tải các phần phụ thuộc của bạn xuống ở chế độ nền.
Android
  1. Làm theo hướng dẫn để thêm Firebase vào ứng dụng Android.
  2. Bằng cách sử dụng BoM trên Android cho Firebase, hãy khai báo phần phụ thuộc cho thư viện Cloud Firestore cho Android trong tệp Gradle của mô-đun (cấp ứng dụng) (thường là app/build.gradle.kts hoặc 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")
    }

    Bằng cách sử dụng BoM trên Android cho Firebase, ứng dụng của bạn sẽ luôn sử dụng những phiên bản tương thích của thư viện Android trên Firebase.

    (Tuỳ chọn) Khai báo phần phụ thuộc của thư viện Firebase mà không cần dùng BoM

    Nếu chọn không sử dụng Firebase BoM, bạn phải chỉ định từng phiên bản thư viện Firebase trong dòng phần phụ thuộc của phiên bản đó.

    Xin lưu ý rằng nếu sử dụng nhiều thư viện Firebase trong ứng dụng, bạn nên sử dụng BoM để quản lý các phiên bản thư viện, nhằm đảm bảo rằng tất cả các phiên bản đều tương thích.

    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")
    }

    Bạn đang tìm kiếm một mô-đun thư viện dành riêng cho Kotlin? Bắt đầu từ bản phát hành tháng 10 năm 2023, cả nhà phát triển Kotlin và Java đều có thể phụ thuộc vào mô-đun thư viện chính (để biết thông tin chi tiết, hãy xem Câu hỏi thường gặp về sáng kiến này).

Dart

  1. Nếu chưa thực hiện, hãy định cấu hình và khởi động Firebase trong ứng dụng Flutter của bạn.
  2. Từ gốc của dự án Flutter, hãy chạy lệnh sau để cài đặt trình bổ trợ:
    flutter pub add cloud_firestore
  3. Sau khi hoàn tất, hãy tạo lại ứng dụng Flutter:
    flutter run
  4. Không bắt buộc: Cải thiện thời gian tạo bản dựng iOS và macOS bằng cách thêm khung được biên dịch trước.

    Hiện tại, Firestore SDK cho iOS phụ thuộc vào mã có thể mất hơn 5 phút để tạo trong Xcode. Để giảm đáng kể thời gian tạo bản dựng, bạn có thể sử dụng phiên bản được biên dịch trước bằng cách thêm dòng này vào khối target 'Runner' do trong 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

    Thay thế IOS_SDK_VERSION bằng phiên bản SDK Firebase iOS được chỉ định trong tệp firebase_sdk_version.rb của firebase_core. Nếu bạn không sử dụng phiên bản mới nhất của firebase_core, hãy tìm tệp này trong bộ nhớ đệm gói Pub cục bộ (thường là ~/.pub-cache).

    Ngoài ra, hãy đảm bảo bạn đã nâng cấp CocoaPods lên phiên bản 1.9.1 trở lên:

    gem install cocoapods

    Để biết thêm thông tin, hãy xem vấn đề trên GitHub.

Java
  1. Thêm Firebase Admin SDK vào ứng dụng của bạn:
    • Sử dụng Gradle:
      compile 'com.google.firebase:firebase-admin:1.32.0'
    • Sử dụng Maven:
      <dependency>
        <groupId>com.google.firebase</groupId>
        <artifactId>firebase-admin</artifactId>
        <version>1.32.0</version>
      </dependency>
           
  2. Hãy làm theo hướng dẫn bên dưới để khởi tạo Cloud Firestore bằng thông tin đăng nhập thích hợp trong môi trường của bạn.
Python
  1. Thêm Firebase Admin SDK vào ứng dụng Python của bạn:
    pip install --upgrade firebase-admin
  2. Hãy làm theo hướng dẫn bên dưới để khởi tạo Cloud Firestore bằng thông tin đăng nhập thích hợp trong môi trường của bạn.
C++
  1. Làm theo hướng dẫn để thêm Firebase vào dự án C++.
  2. Giao diện C++ cho Android.
    • Phần phụ thuộc Gradle. Thêm phần sau vào tệp Gradle của mô-đun (cấp ứng dụng) (thường là 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
              }
              
    • Phần phụ thuộc nhị phân. Tương tự, cách được đề xuất để nhận các phần phụ thuộc nhị phân là thêm nội dung sau vào tệp 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. Để thiết lập tích hợp trên máy tính, hãy xem phần Thêm Firebase vào dự án C++.
Unity
  1. Làm theo hướng dẫn để thêm Firebase vào dự án Unity.
  2. Sử dụng giao diện Unity để định cấu hình dự án nhằm giảm thiểu các bản dựng Android.
  3. Bạn phải giảm thiểu bản dựng để tránh thông báo Error while merging dex archives.

    • Bạn có thể tìm thấy lựa chọn này trong phần Player Settings > Android > Publishing Settings > Minify (Cài đặt trình phát > Android > Cài đặt xuất bản > Giảm thiểu).
    • Các lựa chọn có thể khác nhau trong các phiên bản Unity. Vì vậy, hãy tham khảo tài liệu chính thức của UnityHướng dẫn gỡ lỗi bản dựng Firebase Unity.
    • Nếu sau khi bật tính năng rút gọn, số lượng phương thức được tham chiếu vẫn vượt quá giới hạn, thì bạn có thể bật multidex trong:
      • mainTemplate.gradle nếu bạn bật Custom Gradle Template (Mẫu Gradle tuỳ chỉnh) trong phần Player Settings (Cài đặt trình phát)
      • hoặc tệp build.gradle cấp mô-đun nếu bạn dùng Android Studio để tạo dự án đã xuất.
Node.js
  1. Thêm Firebase Admin SDK vào ứng dụng của bạn:
    npm install firebase-admin --save
  2. Hãy làm theo hướng dẫn bên dưới để khởi tạo Cloud Firestore bằng thông tin đăng nhập thích hợp trong môi trường của bạn.
Tìm
  1. Thêm Firebase Admin SDK vào ứng dụng Go của bạn:
    go get firebase.google.com/go
  2. Hãy làm theo hướng dẫn bên dưới để khởi tạo Cloud Firestore bằng thông tin đăng nhập thích hợp trong môi trường của bạn.
PHP
  1. Thư viện ứng dụng máy chủ Cloud Firestore (Java, Node.js, Python, Go, PHP, C# và Ruby) sử dụng Thông tin xác thực mặc định của ứng dụng trên Google để xác thực.
    • Để xác thực từ môi trường phát triển, hãy đặt biến môi trường GOOGLE_APPLICATION_CREDENTIALS để trỏ đến một tệp khoá tài khoản dịch vụ JSON. Bạn có thể tạo một tệp khoá trên trang Thông tin xác thực API Console.
      export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
    • Trong môi trường phát hành chính thức, bạn không cần xác thực nếu chạy ứng dụng trên App Engine hoặc Compute Engine, bằng cách sử dụng cùng một dự án mà bạn dùng cho Cloud Firestore. Nếu không, hãy thiết lập tài khoản dịch vụ.
  2. Cài đặt và bật tiện ích gRPC cho PHP. Bạn sẽ cần sử dụng tiện ích này để dùng thư viện ứng dụng.
  3. Thêm thư viện Cloud Firestore PHP vào ứng dụng của bạn:
    composer require google/cloud-firestore
C#
  1. Thư viện ứng dụng máy chủ Cloud Firestore (Java, Node.js, Python, Go, PHP, C# và Ruby) sử dụng Thông tin xác thực mặc định của ứng dụng trên Google để xác thực.
    • Để xác thực từ môi trường phát triển, hãy đặt biến môi trường GOOGLE_APPLICATION_CREDENTIALS để trỏ đến một tệp khoá tài khoản dịch vụ JSON. Bạn có thể tạo một tệp khoá trên trang Thông tin xác thực API Console.
      export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
    • Trong môi trường phát hành chính thức, bạn không cần xác thực nếu chạy ứng dụng trên App Engine hoặc Compute Engine, bằng cách sử dụng cùng một dự án mà bạn dùng cho Cloud Firestore. Nếu không, hãy thiết lập tài khoản dịch vụ.
  2. Thêm thư viện Cloud Firestore C# vào ứng dụng của bạn trong tệp .csproj:
    <ItemGroup>
      <PackageReference Include="Google.Cloud.Firestore" Version="1.1.0-beta01" />
    </ItemGroup>
  3. Thêm đoạn mã sau vào tệp Program.cs:
    using Google.Cloud.Firestore;
Ruby
  1. Thư viện ứng dụng máy chủ Cloud Firestore (Java, Node.js, Python, Go, PHP, C# và Ruby) sử dụng Thông tin xác thực mặc định của ứng dụng trên Google để xác thực.
    • Để xác thực từ môi trường phát triển, hãy đặt biến môi trường GOOGLE_APPLICATION_CREDENTIALS để trỏ đến một tệp khoá tài khoản dịch vụ JSON. Bạn có thể tạo một tệp khoá trên trang Thông tin xác thực API Console.
      export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
    • Trong môi trường phát hành chính thức, bạn không cần xác thực nếu chạy ứng dụng trên App Engine hoặc Compute Engine, bằng cách sử dụng cùng một dự án mà bạn dùng cho Cloud Firestore. Nếu không, hãy thiết lập tài khoản dịch vụ.
  2. Thêm thư viện Cloud Firestore Ruby vào ứng dụng của bạn trong Gemfile:
    gem "google-cloud-firestore"
  3. Cài đặt các phần phụ thuộc từ Gemfile bằng cách sử dụng:
    bundle install

(Không bắt buộc) Tạo mẫu và kiểm thử bằng Firebase Local Emulator Suite

Đối với nhà phát triển ứng dụng di động, trước khi nói về cách ứng dụng của bạn ghi và đọc từ Cloud Firestore, hãy giới thiệu một bộ công cụ mà bạn có thể dùng để tạo mẫu và kiểm thử chức năng Cloud Firestore:Firebase Local Emulator Suite. Nếu bạn đang thử nghiệm các mô hình dữ liệu khác nhau, tối ưu hoá các quy tắc bảo mật hoặc tìm cách tương tác với phần phụ trợ hiệu quả nhất về chi phí, thì việc có thể làm việc cục bộ mà không cần triển khai các dịch vụ trực tiếp có thể là một ý tưởng hay.

Trình mô phỏng Cloud Firestore là một phần của Local Emulator Suite, cho phép ứng dụng của bạn tương tác với nội dung và cấu hình cơ sở dữ liệu được mô phỏng, cũng như các tài nguyên dự án được mô phỏng (các hàm, cơ sở dữ liệu khác và quy tắc bảo mật) (nếu có).

Bạn chỉ cần thực hiện vài bước để sử dụng trình mô phỏng Cloud Firestore:

  1. Thêm một dòng mã vào cấu hình kiểm thử của ứng dụng để kết nối với trình mô phỏng.
  2. Từ gốc của thư mục dự án cục bộ, hãy chạy firebase emulators:start.
  3. Thực hiện các lệnh gọi từ mã nguyên mẫu của ứng dụng bằng SDK nền tảng Cloud Firestore như thường lệ.

Bạn có thể xem hướng dẫn chi tiết liên quan đến Cloud FirestoreCloud Functions. Bạn cũng nên xem phần giới thiệu về Local Emulator Suite.

Khởi chạy Cloud Firestore

Khởi chạy một thực thể của 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);

Thay thế FIREBASE_CONFIGURATION bằng firebaseConfig của ứng dụng web.

Để duy trì dữ liệu khi thiết bị mất kết nối, hãy xem tài liệu Bật dữ liệu ngoại tuyế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();

Thay thế FIREBASE_CONFIGURATION bằng firebaseConfig của ứng dụng web.

Để duy trì dữ liệu khi thiết bị mất kết nối, hãy xem tài liệu Bật dữ liệu ngoại tuyến.

Swift
Lưu ý: Sản phẩm này không có trên các mục tiêu watchOS và App Clip.
import FirebaseCore
import FirebaseFirestore
FirebaseApp.configure()

let db = Firestore.firestore()
Objective-C
Lưu ý: Sản phẩm này không có trên các mục tiêu watchOS và App Clip.
@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
SDK Cloud Firestore được khởi chạy theo nhiều cách tuỳ thuộc vào môi trường của bạn. Dưới đây là những phương pháp phổ biến nhất. Để biết thông tin tham khảo đầy đủ, hãy xem phần Khởi chạy Admin SDK.
  • Khởi chạy vào ngày 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();
  • Khởi động trên máy chủ của riêng bạn

    Để sử dụng Firebase Admin SDK trên máy chủ của riêng bạn, hãy sử dụng một tài khoản dịch vụ.

    Chuyển đến IAM và quản trị > Tài khoản dịch vụ trong bảng điều khiển Google Cloud. Tạo khoá riêng tư mới và lưu tệp JSON. Sau đó, hãy dùng tệp này để khởi chạy 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
    SDK Cloud Firestore được khởi chạy theo nhiều cách tuỳ thuộc vào môi trường của bạn. Dưới đây là những phương pháp phổ biến nhất. Để biết thông tin tham khảo đầy đủ, hãy xem phần Khởi chạy Admin SDK.
  • Khởi chạy vào ngày Google Cloud
    import firebase_admin
    from firebase_admin import firestore
    
    # Application Default credentials are automatically created.
    app = firebase_admin.initialize_app()
    db = firestore.client()

    Bạn cũng có thể dùng thông tin đăng nhập mặc định hiện có của ứng dụng để khởi chạy 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()
  • Khởi động trên máy chủ của riêng bạn

    Để sử dụng Firebase Admin SDK trên máy chủ của riêng bạn, hãy sử dụng một tài khoản dịch vụ.

    Chuyển đến IAM và quản trị > Tài khoản dịch vụ trong bảng điều khiển Google Cloud. Tạo khoá riêng tư mới và lưu tệp JSON. Sau đó, hãy dùng tệp này để khởi chạy 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

    SDK Cloud Firestore được khởi chạy theo nhiều cách tuỳ thuộc vào môi trường của bạn. Dưới đây là những phương pháp phổ biến nhất. Để biết thông tin tham khảo đầy đủ, hãy xem phần Khởi chạy Admin SDK.
  • Khởi chạy vào ngày 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()

    Bạn cũng có thể dùng thông tin đăng nhập mặc định hiện có của ứng dụng để khởi chạy 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()
  • Khởi động trên máy chủ của riêng bạn

    Để sử dụng Firebase Admin SDK trên máy chủ của riêng bạn, hãy sử dụng một tài khoản dịch vụ.

    Chuyển đến IAM và quản trị > Tài khoản dịch vụ trong bảng điều khiển Google Cloud. Tạo khoá riêng tư mới và lưu tệp JSON. Sau đó, hãy dùng tệp này để khởi chạy 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
    SDK Cloud Firestore được khởi chạy theo nhiều cách tuỳ thuộc vào môi trường của bạn. Dưới đây là những phương pháp phổ biến nhất. Để biết thông tin tham khảo đầy đủ, hãy xem phần Khởi chạy Admin SDK.
    • Khởi chạy vào ngày Cloud Functions
      const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
      const { getFirestore, Timestamp, FieldValue, Filter } = require('firebase-admin/firestore');
      initializeApp();
      
      const db = getFirestore();
      
    • Khởi chạy vào ngày 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();
    • Khởi động trên máy chủ của riêng bạn

      Để sử dụng Firebase Admin SDK trên máy chủ của riêng bạn (hoặc bất kỳ môi trường Node.js nào khác), hãy sử dụng tài khoản dịch vụ. Chuyển đến phần IAM và quản trị > Tài khoản dịch vụ trong bảng điều khiển Google Cloud. Tạo khoá riêng tư mới và lưu tệp JSON. Sau đó, hãy dùng tệp này để khởi chạy 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();
      
    Tìm
    SDK Cloud Firestore được khởi chạy theo nhiều cách tuỳ thuộc vào môi trường của bạn. Dưới đây là những phương pháp phổ biến nhất. Để biết thông tin tham khảo đầy đủ, hãy xem phần Khởi chạy Admin SDK.
  • Khởi chạy vào ngày 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()
  • Khởi động trên máy chủ của riêng bạn

    Để sử dụng Firebase Admin SDK trên máy chủ của riêng bạn, hãy sử dụng một tài khoản dịch vụ.

    Chuyển đến IAM và quản trị > Tài khoản dịch vụ trong bảng điều khiển Google Cloud. Tạo khoá riêng tư mới và lưu tệp JSON. Sau đó, hãy dùng tệp này để khởi chạy 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

    Để biết thêm thông tin về cách cài đặt và tạo ứng dụng Cloud Firestore, hãy tham khảo Thư viện ứng dụng 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#

    Để biết thêm thông tin về cách cài đặt và tạo ứng dụng Cloud Firestore, hãy tham khảo Thư viện ứng dụng 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."

    Thêm dữ liệu

    Cloud Firestore lưu trữ dữ liệu trong Tài liệu, được lưu trữ trong Bộ sưu tập. Cloud Firestore sẽ tạo các bộ sưu tập và tài liệu một cách ngầm định vào lần đầu tiên bạn thêm dữ liệu vào tài liệu. Bạn không cần phải tạo rõ ràng các bộ sưu tập hoặc tài liệu.

    Tạo một bộ sưu tập và tài liệu mới bằng mã ví dụ sau.

    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
    Lưu ý: Sản phẩm này không có trên các mục tiêu watchOS và App Clip.
    // 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
    Lưu ý: Sản phẩm này không có trên các mục tiêu watchOS và App Clip.
    // 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
    });
    Tìm
    _, _, 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

    Để biết thêm thông tin về cách cài đặt và tạo ứng dụng Cloud Firestore, hãy tham khảo Thư viện ứng dụng 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."

    Bây giờ, hãy thêm một tài liệu khác vào bộ sưu tập users. Xin lưu ý rằng giấy tờ này có một cặp khoá-giá trị (tên đệm) không xuất hiện trong giấy tờ đầu tiên. Các tài liệu trong một bộ sưu tập có thể chứa nhiều nhóm thông tin.

    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
    Lưu ý: Sản phẩm này không có trên các mục tiêu watchOS và App Clip.
    // 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
    Lưu ý: Sản phẩm này không có trên các mục tiêu watchOS và App Clip.
    // 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
    });
    Tìm
    _, _, 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

    Để biết thêm thông tin về cách cài đặt và tạo ứng dụng Cloud Firestore, hãy tham khảo Thư viện ứng dụng 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."

    Đọc dữ liệu

    Sử dụng trình xem dữ liệu trong bảng điều khiển của Firebase để nhanh chóng xác minh rằng bạn đã thêm dữ liệu vào Cloud Firestore.

    Bạn cũng có thể dùng phương thức "get" để truy xuất toàn bộ tập hợp.

    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
    Lưu ý: Sản phẩm này không có trên các mục tiêu watchOS và App Clip.
    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
    Lưu ý: Sản phẩm này không có trên các mục tiêu watchOS và App Clip.
    [[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());
    });
    Tìm
    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

    Để biết thêm thông tin về cách cài đặt và tạo ứng dụng Cloud Firestore, hãy tham khảo Thư viện ứng dụng 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

    Bảo mật dữ liệu của bạn

    Nếu bạn đang sử dụng SDK của nền tảng web, Android hoặc Apple, hãy sử dụng Xác thực FirebaseCloud Firestore Security Rules để bảo mật dữ liệu của bạn trong Cloud Firestore.

    Sau đây là một số bộ quy tắc cơ bản mà bạn có thể sử dụng để bắt đầu. Bạn có thể sửa đổi các quy tắc bảo mật trong thẻ Quy tắc của bảng điều khiển.

    Cần có quyền truy cập

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

    Chế độ khoá

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

    Trước khi triển khai ứng dụng web, Android hoặc iOS vào quy trình phát hành công khai, hãy thực hiện các bước để đảm bảo rằng chỉ các ứng dụng khách của bạn mới có thể truy cập vào dữ liệu Cloud Firestore. Xem tài liệu về App Check.

    Nếu bạn đang sử dụng một trong các SDK máy chủ, hãy dùng Quản lý danh tính và quyền truy cập (IAM) để bảo mật dữ liệu của bạn trong Cloud Firestore.

    Xem video hướng dẫn

    Để biết hướng dẫn chi tiết về cách bắt đầu sử dụng thư viện ứng dụng di động Cloud Firestore, hãy xem một trong các video hướng dẫn sau:

    Web
    iOS+
    Android

    Bạn có thể xem thêm video trên kênh YouTube của Firebase.

    Các bước tiếp theo

    Mở rộng kiến thức của bạn với các chủ đề sau: