เริ่มต้นใช้งาน Firestore Standard Edition โดยใช้ไลบรารีของไคลเอ็นต์เซิร์ฟเวอร์

คู่มือเริ่มใช้งานฉบับย่อนี้จะแสดงวิธีตั้งค่า Firestore Enterprise Edition, เพิ่มข้อมูล แล้วดูข้อมูลที่คุณเพิ่งเพิ่มในคอนโซล Firebase โดยใช้ไลบรารีของไคลเอ็นต์เซิร์ฟเวอร์สำหรับ C#, Go, Java, Node.js, PHP, Python และ Ruby

ใช้ไลบรารีของไคลเอ็นต์เหล่านี้เพื่อตั้งค่าสภาพแวดล้อมของเซิร์ฟเวอร์ที่มีสิทธิ์เข้าถึงฐานข้อมูลของคุณอย่างเต็มรูปแบบ

สร้างฐานข้อมูล Cloud Firestore

  1. หากยังไม่ได้สร้างโปรเจ็กต์ Firebase ให้ไปที่คอนโซล Firebase แล้วคลิกเพิ่มโปรเจ็กต์ จากนั้นทำตามวิธีการบนหน้าจอเพื่อสร้างโปรเจ็กต์ Firebase หรือเพิ่มบริการ Firebase ลงในโปรเจ็กต์ Google Cloud ที่มีอยู่

  2. ในแผงด้านซ้าย ให้ไปที่ฐานข้อมูลและพื้นที่เก็บข้อมูล > Firestore

  3. คลิกสร้างฐานข้อมูล

  4. เลือกสถานที่ตั้งสำหรับฐานข้อมูล

    หากเลือกสถานที่ตั้งไม่ได้ แสดงว่ามีการตั้งค่า "สถานที่ตั้งสำหรับทรัพยากร Google Cloud เริ่มต้น" ของโปรเจ็กต์แล้ว ทรัพยากรบางอย่างของโปรเจ็กต์ (เช่น อินสแตนซ์ Cloud Firestore เริ่มต้น) จะแชร์ทรัพยากรที่ขึ้นอยู่กับตำแหน่งร่วมกัน และสามารถตั้งค่าตำแหน่งได้ในระหว่างการสร้างโปรเจ็กต์หรือเมื่อตั้งค่าบริการอื่นที่แชร์ทรัพยากรที่ขึ้นอยู่กับตำแหน่งนี้

  5. เลือกโหมดเริ่มต้นสำหรับ Cloud Firestore Security Rules ดังนี้

    โหมดทดสอบ

    เหมาะสำหรับการเริ่มต้นใช้งานไลบรารีของไคลเอ็นต์บนอุปกรณ์เคลื่อนที่และเว็บ แต่จะอนุญาตให้ทุกคนอ่านและเขียนทับข้อมูลของคุณได้ หลังจากทดสอบแล้ว อย่าลืมอ่านส่วนรักษาความปลอดภัยของข้อมูล

    หากต้องการเริ่มต้นใช้งาน SDK สำหรับเว็บ, แพลตฟอร์ม Apple หรือ Android ให้เลือกโหมดทดสอบ

    โหมดโปรดักชัน

    ปฏิเสธการอ่านและเขียนทั้งหมดจากไคลเอ็นต์บนอุปกรณ์เคลื่อนที่และเว็บ เซิร์ฟเวอร์แอปพลิเคชันที่ตรวจสอบสิทธิ์แล้ว (C#, Go, Java, Node.js, PHP, Python หรือ Ruby) จะยังคงเข้าถึงฐานข้อมูลของคุณได้

    หากต้องการเริ่มต้นใช้งานไลบรารีของไคลเอ็นต์เซิร์ฟเวอร์ C#, Go, Java, Node.js, PHP, Python หรือ Ruby ให้เลือกโหมดโปรดักชัน

    ชุด Cloud Firestore Security Rules เริ่มต้นจะใช้กับฐานข้อมูล Cloud Firestore เริ่มต้น หากสร้างฐานข้อมูลหลายรายการสำหรับโปรเจ็กต์ คุณจะทำให้ Cloud Firestore Security Rules ใช้งานได้สำหรับแต่ละฐานข้อมูล

  6. คลิกสร้าง

เมื่อเปิดใช้ Cloud Firestore ระบบจะเปิดใช้ API ใน Cloud API Manager ด้วย

ตั้งค่าสภาพแวดล้อมในการพัฒนาซอฟต์แวร์

เพิ่มทรัพยากร Dependency และไลบรารีของไคลเอ็นต์ที่จำเป็นลงในแอป

Java
  1. เพิ่ม Firebase Admin SDK ลงในแอปโดยทำดังนี้
    • การใช้ Gradle
      implementation 'com.google.firebase:firebase-admin:9.11.0'
    • การใช้ Maven:
      <dependency>
        <groupId>com.google.firebase</groupId>
        <artifactId>firebase-admin</artifactId>
        <version>9.11.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"
    • ในสภาพแวดล้อมฮาร์ดแวร์และซอฟต์แวร์ คุณไม่จำเป็นต้องตรวจสอบสิทธิ์หากเรียกใช้แอปพลิเคชันใน App Engine หรือ Compute Engine โดยใช้โปรเจ็กต์เดียวกับที่ใช้สำหรับ Cloud Firestore หรือตั้งค่าบัญชีบริการ
  2. ติดตั้งและเปิดใช้ส่วนขยาย gRPC สำหรับ PHP ซึ่งคุณจะต้องใช้ไลบรารีของไคลเอ็นต์
  3. เพิ่มไลบรารี PHP ของ Cloud Firestore ลงในแอปโดยทำดังนี้
    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"
    • ในสภาพแวดล้อมฮาร์ดแวร์และซอฟต์แวร์ คุณไม่จำเป็นต้องตรวจสอบสิทธิ์หากเรียกใช้แอปพลิเคชันใน App Engine หรือ Compute Engine โดยใช้โปรเจ็กต์เดียวกับที่ใช้สำหรับ Cloud Firestore หรือตั้งค่าบัญชีบริการ
  2. เพิ่มไลบรารี Cloud Firestore Ruby ลงในแอปใน Gemfile:
    gem "google-cloud-firestore"
  3. ติดตั้งทรัพยากร Dependency จาก Gemfile โดยใช้คำสั่งต่อไปนี้
    bundle install

(ไม่บังคับ) สร้างต้นแบบและทดสอบด้วย Firebase Local Emulator Suite

สำหรับนักพัฒนาแอปบนอุปกรณ์เคลื่อนที่ ก่อนที่จะพูดถึงวิธีที่แอปเขียนและอ่านจาก Cloud Firestore เราขอแนะนำชุดเครื่องมือที่คุณสามารถใช้เพื่อสร้างต้นแบบและทดสอบฟังก์ชันการทำงานของ Cloud Firestore ดังนี้ Firebase Local Emulator Suite หากคุณกำลังลองใช้โมเดลข้อมูลต่างๆ เพิ่มประสิทธิภาพกฎความปลอดภัย หรือพยายามหาวิธีที่คุ้มค่าที่สุดในการโต้ตอบกับแบ็กเอนด์ การทำงานในเครื่องโดยไม่ต้องติดตั้งใช้งานบริการแบบเรียลไทม์อาจเป็นแนวคิดที่ดี

โปรแกรมจำลอง Cloud Firestore เป็นส่วนหนึ่งของ Local Emulator Suite ซึ่งช่วยให้แอปของคุณโต้ตอบกับเนื้อหาและการกำหนดค่าฐานข้อมูลที่จำลองขึ้น รวมถึงทรัพยากรโปรเจ็กต์ที่จำลองขึ้น (ฟังก์ชัน ฐานข้อมูลอื่นๆ และกฎความปลอดภัย) ได้ (ไม่บังคับ)

การใช้โปรแกรมจำลอง Cloud Firestore มีเพียงไม่กี่ขั้นตอนดังนี้

  1. การเพิ่มบรรทัดโค้ดลงในการกำหนดค่าการทดสอบของแอปเพื่อเชื่อมต่อกับโปรแกรมจำลอง
  2. จากรูทของไดเรกทอรีโปรเจ็กต์ที่อยู่ในเครื่อง ให้เรียกใช้ firebase emulators:start
  3. การโทรจากโค้ดต้นแบบของแอปโดยใช้ SDK ของแพลตฟอร์ม Cloud Firestore ตามปกติ

ดูคำแนะนำแบบทีละขั้นตอนเกี่ยวกับ Cloud Firestore และ Cloud Functions ได้ นอกจากนี้ คุณควรดูข้อมูลเบื้องต้นเกี่ยวกับ Local Emulator Suite ด้วย

เริ่มต้น Cloud Firestore

เริ่มต้นอินสแตนซ์ของ Cloud Firestore:

Java
SDK ของ Cloud Firestore จะเริ่มต้นในลักษณะที่แตกต่างกันไปตามสภาพแวดล้อมของคุณ วิธีการที่พบบ่อยที่สุดมีดังนี้ ดูข้อมูลอ้างอิงทั้งหมดได้ที่หัวข้อเริ่มต้น Admin SDK
  • เริ่มต้นในวันที่ Google Cloud
    import com.google.auth.oauth2.GoogleCredentials;
    import com.google.cloud.firestore.Firestore;
    
    import com.google.firebase.FirebaseApp;
    import com.google.firebase.FirebaseOptions;
    
    // Use the application default credentials
    GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
    FirebaseOptions options = new FirebaseOptions.Builder()
        .setCredentials(credentials)
        .setProjectId(projectId)
        .build();
    FirebaseApp.initializeApp(options);
    
    Firestore db = FirestoreClient.getFirestore();
  • เริ่มต้นในเซิร์ฟเวอร์ของคุณเอง

    หากต้องการใช้ Firebase Admin SDK บนเซิร์ฟเวอร์ของคุณเอง ให้ใช้บัญชีบริการ

    ไปที่ IAM และผู้ดูแลระบบ > บัญชีบริการในคอนโซล Google Cloud สร้างคีย์ส่วนตัวใหม่และบันทึกไฟล์ JSON จากนั้นใช้ไฟล์เพื่อเริ่มต้น SDK ดังนี้

    import com.google.auth.oauth2.GoogleCredentials;
    import com.google.cloud.firestore.Firestore;
    
    import com.google.firebase.FirebaseApp;
    import com.google.firebase.FirebaseOptions;
    
    // Use a service account
    InputStream serviceAccount = new FileInputStream("path/to/serviceAccount.json");
    GoogleCredentials credentials = GoogleCredentials.fromStream(serviceAccount);
    FirebaseOptions options = new FirebaseOptions.Builder()
        .setCredentials(credentials)
        .build();
    FirebaseApp.initializeApp(options);
    
    Firestore db = FirestoreClient.getFirestore();
  • Python
    SDK ของ Cloud Firestore จะเริ่มต้นในรูปแบบที่แตกต่างกันไปตามสภาพแวดล้อมของคุณ วิธีการที่พบบ่อยที่สุดมีดังนี้ ดูข้อมูลอ้างอิงทั้งหมดได้ที่หัวข้อเริ่มต้น Admin SDK
  • เริ่มต้นในวันที่ Google Cloud
    import firebase_admin
    from firebase_admin import firestore
    
    # Application Default credentials are automatically created.
    app = firebase_admin.initialize_app()
    db = firestore.client()

    นอกจากนี้ คุณยังใช้ข้อมูลเข้าสู่ระบบเริ่มต้นของแอปพลิเคชันที่มีอยู่เพื่อเริ่มต้น SDK ได้ด้วย

    import firebase_admin
    from firebase_admin import credentials
    from firebase_admin import firestore
    
    # Use the application default credentials.
    cred = credentials.ApplicationDefault()
    
    firebase_admin.initialize_app(cred)
    db = firestore.client()
  • เริ่มต้นในเซิร์ฟเวอร์ของคุณเอง

    หากต้องการใช้ Firebase Admin SDK บนเซิร์ฟเวอร์ของคุณเอง ให้ใช้บัญชีบริการ

    ไปที่ IAM และผู้ดูแลระบบ > บัญชีบริการในคอนโซล Google Cloud สร้างคีย์ส่วนตัวใหม่และบันทึกไฟล์ JSON จากนั้นใช้ไฟล์เพื่อเริ่มต้น SDK ดังนี้

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

    SDK ของ Cloud Firestore จะเริ่มต้นในลักษณะที่แตกต่างกันไปตามสภาพแวดล้อมของคุณ วิธีการที่พบบ่อยที่สุดมีดังนี้ ดูข้อมูลอ้างอิงทั้งหมดได้ที่หัวข้อเริ่มต้นใช้งาน Admin SDK
  • เริ่มต้นในวันที่ Google Cloud
    import firebase_admin
    from firebase_admin import firestore_async
    
    # Application Default credentials are automatically created.
    app = firebase_admin.initialize_app()
    db = firestore_async.client()

    นอกจากนี้ คุณยังใช้ข้อมูลเข้าสู่ระบบเริ่มต้นของแอปพลิเคชันที่มีอยู่เพื่อเริ่มต้น SDK ได้ด้วย

    import firebase_admin
    from firebase_admin import credentials
    from firebase_admin import firestore_async
    
    # Use the application default credentials.
    cred = credentials.ApplicationDefault()
    
    firebase_admin.initialize_app(cred)
    db = firestore_async.client()
  • เริ่มต้นในเซิร์ฟเวอร์ของคุณเอง

    หากต้องการใช้ Firebase Admin SDK บนเซิร์ฟเวอร์ของคุณเอง ให้ใช้บัญชีบริการ

    ไปที่ IAM และผู้ดูแลระบบ > บัญชีบริการในคอนโซล Google Cloud สร้างคีย์ส่วนตัวใหม่และบันทึกไฟล์ JSON จากนั้นใช้ไฟล์เพื่อเริ่มต้น SDK ดังนี้

    import firebase_admin
    from firebase_admin import credentials
    from firebase_admin import firestore_async
    
    # Use a service account.
    cred = credentials.Certificate('path/to/serviceAccount.json')
    
    app = firebase_admin.initialize_app(cred)
    
    db = firestore_async.client()
  • Node.js
    SDK ของ Cloud Firestore จะเริ่มต้นในลักษณะที่แตกต่างกันไปตามสภาพแวดล้อมของคุณ วิธีการที่พบบ่อยที่สุดมีดังนี้ ดูข้อมูลอ้างอิงทั้งหมดได้ที่หัวข้อเริ่มต้นใช้งาน Admin SDK
    • เริ่มต้นในวันที่ Cloud Functions
      const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
      const { getFirestore, Timestamp, FieldValue, Filter } = require('firebase-admin/firestore');
      initializeApp();
      
      const db = getFirestore();
      
    • เริ่มต้นในวันที่ Google Cloud
      const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
      const { getFirestore, Timestamp, FieldValue, Filter } = require('firebase-admin/firestore');
      initializeApp({
        credential: applicationDefault()
      });
      
      const db = getFirestore();
    • เริ่มต้นในเซิร์ฟเวอร์ของคุณเอง

      หากต้องการใช้ Firebase Admin SDK บนเซิร์ฟเวอร์ของคุณเอง (หรือสภาพแวดล้อม Node.js อื่นๆ) ให้ใช้บัญชีบริการ ไปที่ IAM และผู้ดูแลระบบ > บัญชีบริการในคอนโซล Google Cloud สร้างคีย์ส่วนตัวใหม่และบันทึกไฟล์ JSON จากนั้นใช้ไฟล์เพื่อเริ่มต้น SDK ดังนี้

      const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
      const { getFirestore, Timestamp, FieldValue, Filter } = require('firebase-admin/firestore');
      const serviceAccount = require('./path/to/serviceAccountKey.json');
      
      initializeApp({
        credential: cert(serviceAccount)
      });
      
      const db = getFirestore();
      
    Go
    SDK ของ Cloud Firestore จะเริ่มต้นในรูปแบบที่แตกต่างกันไปตามสภาพแวดล้อมของคุณ วิธีการที่พบบ่อยที่สุดมีดังนี้ ดูข้อมูลอ้างอิงทั้งหมดได้ที่หัวข้อเริ่มต้นใช้งาน Admin SDK
  • เริ่มต้นในวันที่ Google Cloud
    import (
      "log"
    
      firebase "firebase.google.com/go"
      "google.golang.org/api/option"
    )
    
    // Use the application default credentials
    ctx := context.Background()
    conf := &firebase.Config{ProjectID: projectID}
    app, err := firebase.NewApp(ctx, conf)
    if err != nil {
      log.Fatalln(err)
    }
    
    client, err := app.Firestore(ctx)
    if err != nil {
      log.Fatalln(err)
    }
    defer client.Close()
  • เริ่มต้นในเซิร์ฟเวอร์ของคุณเอง

    หากต้องการใช้ Firebase Admin SDK บนเซิร์ฟเวอร์ของคุณเอง ให้ใช้บัญชีบริการ

    ไปที่ IAM และผู้ดูแลระบบ > บัญชีบริการในคอนโซล Google Cloud สร้างคีย์ส่วนตัวใหม่และบันทึกไฟล์ JSON จากนั้นใช้ไฟล์เพื่อเริ่มต้น SDK ดังนี้

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

    PHP

    ดูข้อมูลเพิ่มเติมเกี่ยวกับการติดตั้งและสร้างไคลเอ็นต์ Cloud Firestore ได้ที่ไลบรารีของไคลเอ็นต์ Cloud Firestore

    use Google\Cloud\Firestore\FirestoreClient;
    
    /**
     * Initialize Cloud Firestore with default project ID.
     */
    function setup_client_create(string $projectId = null)
    {
        // Create the Cloud Firestore client
        if (empty($projectId)) {
            // The `projectId` parameter is optional and represents which project the
            // client will act on behalf of. If not supplied, the client falls back to
            // the default project inferred from the environment.
            $db = new FirestoreClient();
            printf('Created Cloud Firestore client with default project ID.' . PHP_EOL);
        } else {
            $db = new FirestoreClient([
                'projectId' => $projectId,
            ]);
            printf('Created Cloud Firestore client with project ID: %s' . PHP_EOL, $projectId);
        }
    }
    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 จะสร้างคอลเล็กชันและเอกสารโดยนัยในครั้งแรกที่คุณเพิ่มข้อมูลลงในเอกสาร คุณไม่จำเป็นต้องสร้างคอลเล็กชันหรือเอกสารอย่างชัดแจ้ง

    สร้างคอลเล็กชันและเอกสารใหม่โดยใช้โค้ดตัวอย่างต่อไปนี้

    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
    });
    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 โปรดทราบว่าเอกสารนี้มีคู่คีย์-ค่า (ชื่อกลาง) ที่ไม่ปรากฏในเอกสารแรก เอกสารในคอลเล็กชันอาจมีชุดข้อมูลที่แตกต่างกัน

    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
    });
    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 เพื่อยืนยันอย่างรวดเร็วว่าคุณได้เพิ่มข้อมูลลงใน Cloud Firestore แล้ว

    นอกจากนี้ คุณยังใช้เมธอด "get" เพื่อดึงข้อมูลคอลเล็กชันทั้งหมดได้ด้วย

    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());
    });
    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

    ขั้นตอนถัดไป

    เพิ่มพูนความรู้ด้วยหัวข้อต่อไปนี้