서버 클라이언트 라이브러리를 사용하여 Cloud Firestore Standard 버전 시작하기

이 빠른 시작에서는 Cloud Firestore Enterprise 버전을 설정하고, 데이터를 추가한 후, C#, Go, Java, Node.js, PHP, Python, Ruby용 서버 클라이언트 라이브러리를 사용하여 Firebase Console에서 방금 추가한 데이터를 보는 방법을 보여줍니다.

이러한 클라이언트 라이브러리를 사용하여 데이터베이스에 대한 전체 액세스 권한이 있는 권한 서버 환경을 설정합니다.

Cloud Firestore 데이터베이스 만들기

  1. Firebase 프로젝트를 아직 만들지 않았다면 Firebase Console에서 프로젝트 추가를 클릭한 후 화면에 표시된 안내를 따라 Firebase 프로젝트를 만들거나 기존 Google Cloud 프로젝트에 Firebase 서비스를 추가합니다.

  2. Firebase Console에서 프로젝트를 엽니다. 왼쪽 패널에서 빌드를 펼친 다음 Firestore 데이터베이스를 선택합니다.

  3. 데이터베이스 만들기를 클릭합니다.

  4. 데이터베이스의 위치를 선택합니다.

    위치를 선택할 수 없다면 프로젝트의 '기본 Google Cloud 리소스의 위치'가 이미 설정된 것입니다. 일부 프로젝트 리소스(예: 기본 Cloud Firestore 인스턴스)는 공통 위치 종속 항목을 공유하며, 위치는 프로젝트 생성 중이나 이 위치 종속 항목을 공유하는 다른 서비스를 설정할 때 설정할 수 있습니다.

  5. Cloud Firestore Security Rules의 시작 모드를 선택합니다.

    테스트 모드

    모바일 및 웹 클라이언트 라이브러리를 시작할 때 유용하지만 모든 사용자가 데이터를 읽고 덮어쓸 수 있습니다. 테스트 완료 후 데이터 보안 섹션을 검토해야 합니다.

    웹, Apple 플랫폼 또는 Android SDK를 시작하려면 테스트 모드를 선택하세요.

    프로덕션 모드

    모바일 및 웹 클라이언트의 모든 읽기 및 쓰기를 거부합니다. 인증된 애플리케이션 서버(C#, Go, 자바, Node.js, PHP, Python, Ruby)에서는 사용자의 데이터베이스에 계속 액세스할 수 있습니다.

    C#, Go, Java, Node.js, PHP, Python 또는 Ruby 서버 클라이언트 라이브러리를 시작하려면 프로덕션 모드를 선택하세요.

    Cloud Firestore Security Rules의 초기 집합이 기본 Cloud Firestore 데이터베이스에 적용됩니다. 프로젝트에 데이터베이스를 여러 개 만드는 경우 각 데이터베이스에 Cloud Firestore Security Rules를 배포할 수 있습니다.

  6. 만들기를 클릭합니다.

Cloud Firestore를 사용 설정하면 Cloud API Manager의 API도 사용 설정됩니다.

개발 환경 설정

필요한 종속 항목 및 클라이언트 라이브러리를 앱에 추가하세요.

자바
  1. Firebase Admin SDK를 앱에 추가합니다.
    • Gradle 사용:
      implementation 'com.google.firebase:firebase-admin:9.7.0'
    • Maven 사용:
      <dependency>
        <groupId>com.google.firebase</groupId>
        <artifactId>firebase-admin</artifactId>
        <version>9.7.0</version>
      </dependency>
           
  2. 아래 안내에 따라 사용자 환경에서 적절한 사용자 인증 정보를 사용해 Cloud Firestore를 초기화합니다.
Python
  1. Firebase Admin SDK를 Python 앱에 추가합니다.
    pip install --upgrade firebase-admin
  2. 아래 안내에 따라 사용자 환경에서 적절한 사용자 인증 정보를 사용해 Cloud Firestore를 초기화합니다.
Node.js
  1. Firebase Admin SDK를 앱에 추가합니다.
    npm install firebase-admin --save
  2. 아래 안내에 따라 사용자 환경에서 적절한 사용자 인증 정보를 사용해 Cloud Firestore를 초기화합니다.
Go
  1. Firebase Admin SDK를 Go 앱에 추가합니다.
    go get firebase.google.com/go
  2. 아래 안내에 따라 사용자 환경에서 적절한 사용자 인증 정보를 사용해 Cloud Firestore를 초기화합니다.
PHP
  1. Cloud Firestore 서버 클라이언트 라이브러리(Java, Node.js, Python, Go, PHP, C#, Ruby)는 인증을 위해 Google 애플리케이션 기본 사용자 인증 정보를 사용합니다.
    • 개발 환경에서 인증하려면 GOOGLE_APPLICATION_CREDENTIALS 환경 변수가 JSON 서비스 계정 키 파일을 가리키도록 설정합니다. API 콘솔 사용자 인증 정보 페이지에서 키 파일을 만들 수 있습니다.
      export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
    • 프로덕션 환경에서는 Cloud Firestore에 사용하는 것과 동일한 프로젝트를 사용하여 App Engine이나 Compute Engine에서 애플리케이션을 실행하는 경우 인증할 필요가 없습니다. 그 외의 경우는 서비스 계정을 설정합니다.
  2. 클라이언트 라이브러리를 사용하는 데 필요한 PHP용 gRPC 확장 프로그램을 설치하고 사용 설정합니다.
  3. Cloud Firestore PHP 라이브러리를 앱에 추가합니다.
    composer require google/cloud-firestore
Ruby
  1. Cloud Firestore 서버 클라이언트 라이브러리(Java, Node.js, Python, Go, PHP, C#, Ruby)는 인증을 위해 Google 애플리케이션 기본 사용자 인증 정보를 사용합니다.
    • 개발 환경에서 인증하려면 GOOGLE_APPLICATION_CREDENTIALS 환경 변수가 JSON 서비스 계정 키 파일을 가리키도록 설정합니다. API 콘솔 사용자 인증 정보 페이지에서 키 파일을 만들 수 있습니다.
      export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
    • 프로덕션 환경에서는 Cloud Firestore에 사용하는 것과 동일한 프로젝트를 사용하여 App Engine이나 Compute Engine에서 애플리케이션을 실행하는 경우 인증할 필요가 없습니다. 그 외의 경우는 서비스 계정을 설정합니다.
  2. Cloud Firestore Ruby 라이브러리를 Gemfile의 앱에 추가합니다.
    gem "google-cloud-firestore"
  3. 다음을 사용하여 Gemfile의 종속 항목을 설치합니다.
    bundle install

(선택사항) Firebase Local Emulator Suite으로 프로토타입 제작 및 테스트

모바일 개발자를 대상으로 앱이 Cloud Firestore에서 데이터를 읽고 쓰는 방법에 대해 설명하기 전에 Cloud Cloud Firestore 기능을 프로토타입으로 제작하고 테스트하는 데 사용할 수 있는 도구 모음인 Firebase Local Emulator Suite를 소개하려 합니다. 다양한 데이터 모델을 사용해 보거나, 보안 규칙을 최적화하거나, 백엔드와 상호작용할 수 있는 가장 비용 효율적인 방법을 찾는 경우 실시간 서비스를 배포하지 않고 로컬에서 작업할 수 있다는 것은 획기적인 아이디어입니다.

Cloud Firestore 에뮬레이터는 Local Emulator Suite의 일부이며 앱에서 에뮬레이션된 데이터베이스 콘텐츠와 구성은 물론 필요에 따라 에뮬레이션된 프로젝트 리소스(함수, 기타 데이터베이스, 보안 규칙)와 상호작용할 수 있게 해줍니다.

Cloud Firestore 에뮬레이터를 사용하려면 다음 몇 단계만 거치면 됩니다.

  1. 에뮬레이터에 연결하려면 앱의 테스트 구성에 코드 줄을 추가합니다.
  2. 로컬 프로젝트 디렉터리의 루트에서 firebase emulators:start를 실행합니다.
  3. 평소와 같이 Cloud Firestore 플랫폼 SDK를 사용하여 앱의 프로토타입 코드에서 호출합니다.

자세한 내용은 Cloud FirestoreCloud Functions 관련 둘러보기를 참조하세요. Local Emulator Suite 소개도 살펴보세요.

Cloud Firestore 초기화

Cloud Firestore의 인스턴스를 초기화합니다.

자바
Cloud Firestore SDK는 환경에 따라 다양한 방식으로 초기화됩니다. 가장 일반적인 방법은 아래와 같습니다. 전체 참조를 보려면 Admin SDK 초기화를 참조하세요.
  • Google Cloud에서 초기화
    import com.google.auth.oauth2.GoogleCredentials;
    import com.google.cloud.firestore.Firestore;
    
    import com.google.firebase.FirebaseApp;
    import com.google.firebase.FirebaseOptions;
    
    // Use the application default credentials
    GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
    FirebaseOptions options = new FirebaseOptions.Builder()
        .setCredentials(credentials)
        .setProjectId(projectId)
        .build();
    FirebaseApp.initializeApp(options);
    
    Firestore db = FirestoreClient.getFirestore();
  • 자체 서버에서 초기화

    자체 서버에서 Firebase Admin SDK를 사용하려면 서비스 계정을 사용합니다.

    Google Cloud 콘솔에서 IAM 및 관리자 > 서비스 계정으로 이동합니다. 새 비공개 키를 생성하고 JSON 파일을 저장합니다. 그런 다음 이 파일을 사용하여 SDK를 초기화합니다.

    import com.google.auth.oauth2.GoogleCredentials;
    import com.google.cloud.firestore.Firestore;
    
    import com.google.firebase.FirebaseApp;
    import com.google.firebase.FirebaseOptions;
    
    // Use a service account
    InputStream serviceAccount = new FileInputStream("path/to/serviceAccount.json");
    GoogleCredentials credentials = GoogleCredentials.fromStream(serviceAccount);
    FirebaseOptions options = new FirebaseOptions.Builder()
        .setCredentials(credentials)
        .build();
    FirebaseApp.initializeApp(options);
    
    Firestore db = FirestoreClient.getFirestore();
  • Python
    Cloud Firestore SDK는 환경에 따라 다양한 방식으로 초기화됩니다. 가장 일반적인 방법은 아래와 같습니다. 전체 참조를 보려면 Admin SDK 초기화를 참조하세요.
  • Google Cloud에서 초기화
    import firebase_admin
    from firebase_admin import firestore
    
    # Application Default credentials are automatically created.
    app = firebase_admin.initialize_app()
    db = firestore.client()

    기존 애플리케이션 기본 사용자 인증 정보를 사용하여 SDK를 초기화할 수도 있습니다.

    import firebase_admin
    from firebase_admin import credentials
    from firebase_admin import firestore
    
    # Use the application default credentials.
    cred = credentials.ApplicationDefault()
    
    firebase_admin.initialize_app(cred)
    db = firestore.client()
  • 자체 서버에서 초기화

    자체 서버에서 Firebase Admin SDK를 사용하려면 서비스 계정을 사용합니다.

    Google Cloud 콘솔에서 IAM 및 관리자 > 서비스 계정으로 이동합니다. 새 비공개 키를 생성하고 JSON 파일을 저장합니다. 그런 다음 이 파일을 사용하여 SDK를 초기화합니다.

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

    Cloud Firestore SDK는 환경에 따라 다양한 방식으로 초기화됩니다. 가장 일반적인 방법은 아래와 같습니다. 전체 참조를 보려면 Admin SDK 초기화를 참조하세요.
  • Google Cloud에서 초기화
    import firebase_admin
    from firebase_admin import firestore_async
    
    # Application Default credentials are automatically created.
    app = firebase_admin.initialize_app()
    db = firestore_async.client()

    기존 애플리케이션 기본 사용자 인증 정보를 사용하여 SDK를 초기화할 수도 있습니다.

    import firebase_admin
    from firebase_admin import credentials
    from firebase_admin import firestore_async
    
    # Use the application default credentials.
    cred = credentials.ApplicationDefault()
    
    firebase_admin.initialize_app(cred)
    db = firestore_async.client()
  • 자체 서버에서 초기화

    자체 서버에서 Firebase Admin SDK를 사용하려면 서비스 계정을 사용합니다.

    Google Cloud 콘솔에서 IAM 및 관리자 > 서비스 계정으로 이동합니다. 새 비공개 키를 생성하고 JSON 파일을 저장합니다. 그런 다음 이 파일을 사용하여 SDK를 초기화합니다.

    import firebase_admin
    from firebase_admin import credentials
    from firebase_admin import firestore_async
    
    # Use a service account.
    cred = credentials.Certificate('path/to/serviceAccount.json')
    
    app = firebase_admin.initialize_app(cred)
    
    db = firestore_async.client()
  • Node.js
    Cloud Firestore SDK는 환경에 따라 다양한 방식으로 초기화됩니다. 가장 일반적인 방법은 아래와 같습니다. 전체 참조를 보려면 Admin SDK 초기화를 참조하세요.
    • Cloud Functions에서 초기화
      const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
      const { getFirestore, Timestamp, FieldValue, Filter } = require('firebase-admin/firestore');
      initializeApp();
      
      const db = getFirestore();
      
    • Google Cloud에서 초기화
      const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
      const { getFirestore, Timestamp, FieldValue, Filter } = require('firebase-admin/firestore');
      initializeApp({
        credential: applicationDefault()
      });
      
      const db = getFirestore();
    • 자체 서버에서 초기화

      자체 서버(또는 다른 Node.js 환경)에서 Firebase Admin SDK를 사용하려면 서비스 계정을 사용합니다. Google Cloud 콘솔에서 IAM 및 관리자 > 서비스 계정으로 이동합니다. 새 비공개 키를 생성하고 JSON 파일을 저장합니다. 그런 다음 이 파일을 사용하여 SDK를 초기화합니다.

      const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
      const { getFirestore, Timestamp, FieldValue, Filter } = require('firebase-admin/firestore');
      const serviceAccount = require('./path/to/serviceAccountKey.json');
      
      initializeApp({
        credential: cert(serviceAccount)
      });
      
      const db = getFirestore();
      
    Go
    Cloud Firestore SDK는 환경에 따라 다양한 방식으로 초기화됩니다. 가장 일반적인 방법은 아래와 같습니다. 전체 참조를 보려면 Admin SDK 초기화를 참조하세요.
  • Google Cloud에서 초기화
    import (
      "log"
    
      firebase "firebase.google.com/go"
      "google.golang.org/api/option"
    )
    
    // Use the application default credentials
    ctx := context.Background()
    conf := &firebase.Config{ProjectID: projectID}
    app, err := firebase.NewApp(ctx, conf)
    if err != nil {
      log.Fatalln(err)
    }
    
    client, err := app.Firestore(ctx)
    if err != nil {
      log.Fatalln(err)
    }
    defer client.Close()
  • 자체 서버에서 초기화

    자체 서버에서 Firebase Admin SDK를 사용하려면 서비스 계정을 사용합니다.

    Google Cloud 콘솔에서 IAM 및 관리자 > 서비스 계정으로 이동합니다. 새 비공개 키를 생성하고 JSON 파일을 저장합니다. 그런 다음 이 파일을 사용하여 SDK를 초기화합니다.

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

    PHP

    Cloud Firestore 클라이언트 설치 및 생성에 관한 자세한 내용은 Cloud Firestore 클라이언트 라이브러리를 참조하세요.

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

    C#

    Cloud Firestore 클라이언트 설치 및 생성에 관한 자세한 내용은 Cloud Firestore 클라이언트 라이브러리를 참조하세요.

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

    데이터 추가

    Cloud Firestore는 컬렉션에 저장되는 문서에 데이터를 저장합니다. 문서에 데이터를 처음 추가할 때 Cloud Firestore는 암시적으로 컬렉션과 문서를 만듭니다. 컬렉션이나 문서를 명시적으로 만들 필요가 없습니다.

    다음 예시 코드를 사용해 새 컬렉션과 문서를 만듭니다.

    자바
    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
    });
    Go
    _, _, err := client.Collection("users").Add(ctx, map[string]interface{}{
    	"first": "Ada",
    	"last":  "Lovelace",
    	"born":  1815,
    })
    if err != nil {
    	log.Fatalf("Failed adding alovelace: %v", err)
    }
    PHP

    PHP

    Cloud Firestore 클라이언트 설치 및 생성에 관한 자세한 내용은 Cloud Firestore 클라이언트 라이브러리를 참조하세요.

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

    이제 users 컬렉션에 다른 문서를 추가합니다. 첫 번째 문서에는 나타나지 않는 키-값 쌍(중간 이름)이 문서에 포함된다는 점에 유의하세요. 컬렉션의 문서에는 다른 정보 집합이 포함될 수 있습니다.

    자바
    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
    });
    Go
    _, _, err = client.Collection("users").Add(ctx, map[string]interface{}{
    	"first":  "Alan",
    	"middle": "Mathison",
    	"last":   "Turing",
    	"born":   1912,
    })
    if err != nil {
    	log.Fatalf("Failed adding aturing: %v", err)
    }
    PHP

    PHP

    Cloud Firestore 클라이언트 설치 및 생성에 관한 자세한 내용은 Cloud Firestore 클라이언트 라이브러리를 참조하세요.

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

    데이터 읽기

    Firebase Console의 데이터 뷰어를 사용하여 Cloud Firestore에 추가한 데이터를 빠르게 확인합니다.

    'get' 메서드를 사용해 전체 컬렉션을 가져올 수도 있습니다.

    자바
    // 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());
    });
    Go
    iter := client.Collection("users").Documents(ctx)
    for {
    	doc, err := iter.Next()
    	if err == iterator.Done {
    		break
    	}
    	if err != nil {
    		log.Fatalf("Failed to iterate: %v", err)
    	}
    	fmt.Println(doc.Data())
    }
    PHP

    PHP

    Cloud Firestore 클라이언트 설치 및 생성에 관한 자세한 내용은 Cloud Firestore 클라이언트 라이브러리를 참조하세요.

    $usersRef = $db->collection('samples/php/users');
    $snapshot = $usersRef->documents();
    foreach ($snapshot as $user) {
        printf('User: %s' . PHP_EOL, $user->id());
        printf('First: %s' . PHP_EOL, $user['first']);
        if (!empty($user['middle'])) {
            printf('Middle: %s' . PHP_EOL, $user['middle']);
        }
        printf('Last: %s' . PHP_EOL, $user['last']);
        printf('Born: %d' . PHP_EOL, $user['born']);
        printf(PHP_EOL);
    }
    printf('Retrieved and printed out all documents from the users collection.' . PHP_EOL);
    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

    다음 단계

    다음 주제를 자세히 알아보세요.