Bắt đầu sử dụng Firestore phiên bản Chuẩn bằng thư viện ứng dụng máy chủ

Hướng dẫn nhanh này trình bày cách thiết lập phiên bản Firestore Enterprise, thêm dữ liệu, sau đó xem dữ liệu bạn vừa thêm vào bảng điều khiển của Firebase bằng thư viện ứng dụng máy chủ cho C#, Go, Java, Node.js, PHP, Python và Ruby.

Sử dụng các thư viện ứng dụng này để thiết lập môi trường máy chủ đặc quyền có quyền truy cập đầy đủ vào cơ sở dữ liệu của bạn.

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

  1. Nếu bạn chưa tạo dự án Firebase, hãy làm như sau: Trong bảng điều khiển của 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 dự án Firebase hoặc thêm dịch vụ Firebase vào một dự án Google Cloud hiện có.

  2. Trong bảng điều khiển bên trái, hãy chuyển đến Databases & Storage (Cơ sở dữ liệu và bộ nhớ) > 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 bạn không thể chọn một vị trí, thì tức là "vị trí cho tài nguyên Google Cloud mặc định" của dự án đã được đặt. Một số tài nguyên trong dự án của bạn (chẳng hạn như thực thể Cloud Firestore mặc định) có chung một phần phụ thuộc về 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 có chung phần phụ thuộc về vị trí này.

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

    Chế độ thử nghiệm

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

    Để bắt đầu sử dụng SDK cho web, nền tảng của Apple hoặc SDK Android, hãy chọn chế độ thử nghiệm.

    Chế độ sản xuất

    Từ chối tất cả các yêu cầu đọc và ghi từ ứng dụng di động và ứng dụng web. Máy chủ ứng dụng đã xác thực của bạn (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ế độ sản xuất.

    Tập hợp 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 của Cloud.

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.

Java
  1. Thêm SDK của Firebase dành cho quản trị viên vào ứng dụng của bạn:
    • Sử dụng Gradle:
      implementation 'com.google.firebase:firebase-admin:9.11.0'
    • Sử dụng Maven:
      <dependency>
        <groupId>com.google.firebase</groupId>
        <artifactId>firebase-admin</artifactId>
        <version>9.11.0</version>
      </dependency>
           
  2. Hãy làm theo hướng dẫn bên dưới để khởi động Cloud Firestore bằng thông tin xác thực phù hợp trong môi trường của bạn.
Python
  1. Thêm SDK của Firebase dành cho quản trị viên vào ứng dụng Python:
    pip install --upgrade firebase-admin
  2. Hãy làm theo hướng dẫn bên dưới để khởi động Cloud Firestore bằng thông tin xác thực phù hợp trong môi trường của bạn.
Node.js
  1. Thêm SDK của Firebase dành cho quản trị viên 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 động Cloud Firestore bằng thông tin xác thực phù hợp trong môi trường của bạn.
Bắt đầu
  1. Thêm SDK của Firebase dành cho quản trị viên vào ứng dụng Go:
    go get firebase.google.com/go
  2. Hãy làm theo hướng dẫn bên dưới để khởi động Cloud Firestore bằng thông tin xác thực phù 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 tệp khoá tài khoản dịch vụ JSON. Bạn có thể tạo tệp khoá trên trang Thông tin xác thực của API Console.
      export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
    • Trong môi trường thực tế, 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, 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 tiện ích này để sử dụng thư viện ứng dụng.
  3. Thêm thư viện PHP Cloud Firestore vào ứng dụng của bạn:
    composer require 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 tệp khoá tài khoản dịch vụ JSON. Bạn có thể tạo tệp khoá trên trang Thông tin xác thực của API Console.
      export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
    • Trong môi trường thực tế, 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, 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 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 nguyên mẫu và thử nghiệm bằng Firebase Local Emulator Suite

Đối với nhà phát triển thiết bị 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 nguyên mẫu và kiểm thử chức năng của Cloud Firestore: Firebase Local Emulator Suite. Nếu bạn đang thử các mô hình dữ liệu khác nhau, tối ưu hoá quy tắc bảo mật hoặc tìm cách tương tác với phần phụ trợ sao cho tiết kiệm chi phí nhất, 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 (hàm, cơ sở dữ liệu khác và quy tắc bảo mật).

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. Chạy firebase emulators:start từ thư mục gốc của thư mục dự án cục bộ.
  3. Thực hiện 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ư bình thường.

Bạn có thể xem hướng dẫn chi tiết về Cloud Firestore và Cloud 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 động một thực thể của Cloud Firestore:

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 thức phổ biến nhất. Để xem tài liệu tham khảo đầy đủ, hãy xem bài viết Khởi chạy SDK quản trị.
  • Khởi động 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 chạy trên máy chủ của riêng bạn

    Để sử dụng SDK của Firebase dành cho quản trị viên 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 phần IAM & admin > Service accounts (IAM và quản trị > Tài khoản dịch vụ) trong Google Cloud Console. Tạo một khoá riêng tư mới rồi lưu tệp JSON. Sau đó, hãy sử 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 thức phổ biến nhất. Để xem tài liệu tham khảo đầy đủ, hãy xem bài viết Khởi chạy SDK quản trị.
  • Khởi động 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ể sử dụng thông tin xác thực 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 chạy trên máy chủ của riêng bạn

    Để sử dụng SDK của Firebase dành cho quản trị viên 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 phần IAM & admin > Service accounts (IAM và quản trị > Tài khoản dịch vụ) trong Google Cloud Console. Tạo một khoá riêng tư mới rồi lưu tệp JSON. Sau đó, hãy sử 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 thức phổ biến nhất. Để xem tài liệu tham khảo đầy đủ, hãy xem bài viết Khởi chạy SDK quản trị.
  • Khởi động 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ể sử dụng thông tin xác thực 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 chạy trên máy chủ của riêng bạn

    Để sử dụng SDK của Firebase dành cho quản trị viên 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 phần IAM & admin > Service accounts (IAM và quản trị > Tài khoản dịch vụ) trong Google Cloud Console. Tạo một khoá riêng tư mới và lưu tệp JSON. Sau đó, hãy sử 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()
  • 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 thức phổ biến nhất. Để xem tài liệu tham khảo đầy đủ, hãy xem bài viết Khởi chạy SDK quản trị.
    • Khởi động 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 động 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 chạy trên máy chủ của riêng bạn

      Để sử dụng SDK của Firebase dành cho quản trị viên 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 một tài khoản dịch vụ. Chuyển đến phần IAM & admin > Service accounts (IAM và quản trị > Tài khoản dịch vụ) trong Google Cloud Console. Tạo một khoá riêng tư mới rồi lưu tệp JSON. Sau đó, hãy sử 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();
      
    Bắt đầu
    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 thức phổ biến nhất. Để xem tài liệu tham khảo đầy đủ, hãy xem bài viết Khởi chạy SDK quản trị.
  • Khởi động 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 chạy trên máy chủ của riêng bạn

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

    Chuyển đến phần IAM & admin > Service accounts (IAM và quản trị > Tài khoản dịch vụ) trong Google Cloud Console. Tạo một khoá riêng tư mới rồi lưu tệp JSON. Sau đó, hãy sử 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 bài viết 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);
        }
    }
    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 bài viết 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 ngầm tạo các tập hợp và tài liệu trong 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 bộ sưu tập hoặc tài liệu một cách rõ ràng.

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

    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})
    Node.js
    const docRef = db.collection('users').doc('alovelace');
    
    await docRef.set({
      first: 'Ada',
      last: 'Lovelace',
      born: 1815
    });
    Bắt đầu
    _, _, 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 bài viết 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);
    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. Lưu ý rằng tài liệu này bao gồm một cặp khoá-giá trị (tên đệm) không xuất hiện trong tài liệu đầu tiên. Các tài liệu trong một tập hợp có thể chứa nhiều nhóm thông tin.

    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}
    )
    Node.js
    const aTuringRef = db.collection('users').doc('aturing');
    
    await aTuringRef.set({
      'first': 'Alan',
      'middle': 'Mathison',
      'last': 'Turing',
      'born': 1912
    });
    Bắt đầu
    _, _, 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 bài viết 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);
    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ể sử dụng phương thức "get" để truy xuất toàn bộ tập hợp.

    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()}")
    Node.js
    const snapshot = await db.collection('users').get();
    snapshot.forEach((doc) => {
      console.log(doc.id, '=>', doc.data());
    });
    Bắt đầu
    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 bài viết 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);
    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

    Các bước tiếp theo

    Tìm hiểu sâu hơn về các chủ đề sau: