เริ่มต้นใช้งาน Cloud Firestore

การเริ่มต้นอย่างรวดเร็วนี้จะแสดงวิธีตั้งค่า Cloud Firestore, เพิ่มข้อมูล แล้วดู ข้อมูลที่คุณเพิ่งเพิ่มในคอนโซล Firebase

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

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

  2. ไปที่ส่วน Cloud Firestore ของ คอนโซล Firebase ระบบจะแจ้งให้คุณเลือกโปรเจ็กต์ Firebase ที่มีอยู่ ทำตามขั้นตอนการสร้างฐานข้อมูล

  3. เลือกโหมดเริ่มต้นสำหรับกฎความปลอดภัยของ Cloud Firestore

    โหมดทดสอบ

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

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

    โหมดล็อกขณะคุมสอบ

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

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

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

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

    • การตั้งค่าตำแหน่งนี้เป็นของโปรเจ็กต์ ตำแหน่งทรัพยากรเริ่มต้นของ Google Cloud Platform (GCP) โปรดทราบว่าตำแหน่งที่ตั้งนี้จะใช้สำหรับบริการ GCP ในโปรเจ็กต์ของคุณ ที่ต้องการการตั้งค่าตำแหน่งโดยเฉพาะอย่างยิ่ง ที่เก็บข้อมูล Cloud Storage และที่เก็บข้อมูล แอป App Engine (ซึ่งก็คือ หากใช้ Cloud Scheduler)

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

  5. คลิกเสร็จสิ้น

การเปิดใช้ Cloud Firestore จะเป็นการเปิดใช้ API ใน Cloud API Manager

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

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

Web

  1. ทำตามวิธีการเพื่อ เพิ่ม Firebase ไปยังเว็บแอป
  2. เพิ่มไลบรารี Firebase และ Cloud Firestore ลงในแอปโดยทำดังนี้
    <script src="https://www.gstatic.com/firebasejs/10.12.3/firebase-app-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/10.12.3/firebase-firestore-compat.js"></script>
    Cloud Firestore SDK มีให้บริการเป็นแพ็กเกจ npm ด้วย
    npm install firebase@10.12.3 --save
    
    คุณจะต้องมีทั้ง Firebase และ Cloud Firestore ด้วยตนเอง
    import firebase from "firebase/compat/app";
    // Required for side-effects
    import "firebase/firestore";
    

Web

  1. ทำตามวิธีการเพื่อ เพิ่ม Firebase ไปยังเว็บแอป
  2. Cloud Firestore SDK พร้อมให้บริการเป็นแพ็กเกจ npm
    npm install firebase@10.12.3 --save
    
    คุณจะต้องนำเข้าทั้ง Firebase และ Cloud Firestore
    import { initializeApp } from "firebase/app";
    import { getFirestore } from "firebase/firestore";
    
iOS ขึ้นไป

ทำตามวิธีการเพื่อ เพิ่ม Firebase ไปยังแอป Apple

ใช้ Swift Package Manager เพื่อติดตั้งและจัดการทรัพยากร Dependency ของ Firebase

  1. เปิดโปรเจ็กต์แอปใน Xcode แล้วไปที่ไฟล์ > แพ็กเกจ Swift > เพิ่มทรัพยากร Dependency ของแพ็กเกจ
  2. เมื่อได้รับข้อความแจ้ง ให้เพิ่มที่เก็บ SDK สำหรับแพลตฟอร์ม Firebase ของ Apple ดังนี้
  3.   https://github.com/firebase/firebase-ios-sdk
      
  4. เลือกไลบรารี Firestore
  5. เมื่อเสร็จแล้ว Xcode จะเริ่มแก้ปัญหาและดาวน์โหลด ทรัพยากร Dependency ในเบื้องหลัง
Android
  1. ทำตามวิธีการเพื่อ เพิ่ม Firebase ไปยังแอป Android
  2. การใช้ Firebase Android BoM ประกาศทรัพยากร Dependency สำหรับไลบรารี Cloud Firestore สำหรับ Android ใน ไฟล์ Gradle ของโมดูล (ระดับแอป) ของคุณ (ปกติคือ app/build.gradle.kts หรือ app/build.gradle)
    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:33.1.2"))
    
        // Declare the dependency for the Cloud Firestore library
        // When using the BoM, you don't specify versions in Firebase library dependencies
        implementation("com.google.firebase:firebase-firestore")
    }
    

    โดยการใช้ Firebase Android BoM แอปจะใช้ Firebase Android เวอร์ชันที่เข้ากันได้เสมอ ห้องสมุด

    (ทางเลือก) ประกาศทรัพยากร Dependency ของไลบรารี Firebase โดยไม่มีการใช้เอลิเมนต์ บอม

    หากคุณเลือกไม่ใช้ Firebase BoM คุณต้องระบุแต่ละ เวอร์ชันไลบรารี Firebase ในบรรทัดทรัพยากร Dependency

    โปรดทราบว่าหากคุณใช้ไลบรารี Firebase หลายรายการใน ในแอปของคุณ เราขอแนะนำเป็นอย่างยิ่งให้ใช้ BoM ในการจัดการไลบรารี เวอร์ชันต่างๆ เข้าด้วยกันเพื่อให้มั่นใจว่าทุกเวอร์ชันสามารถใช้งานร่วมกันได้

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

    หากกำลังมองหาโมดูลไลบรารีสำหรับ Kotlin โดยเฉพาะ เริ่มต้นด้วย รุ่นเดือนตุลาคม 2023, ทั้งนักพัฒนา Kotlin และ Java สามารถใช้โมดูลไลบรารีหลักได้ (โปรดดูรายละเอียดที่ คําถามที่พบบ่อยเกี่ยวกับโครงการริเริ่มนี้)

Dart

  1. หากยังไม่ได้ดำเนินการ ให้กำหนดค่าและ เริ่มต้น Firebase ในแอป Flutter
  2. จากรูทของโปรเจ็กต์ Flutter ให้เรียกใช้คำสั่งต่อไปนี้เพื่อ ติดตั้งปลั๊กอิน โดยทำดังนี้
    flutter pub add cloud_firestore
  3. เมื่อดำเนินการเสร็จแล้ว ให้สร้างแอปพลิเคชัน Flutter ใหม่โดยทำดังนี้
    flutter run
  4. ไม่บังคับ: ปรับปรุง iOS และ เวลาบิลด์ของ macOS โดยรวม ที่เรียบเรียงไว้ล่วงหน้า

    ปัจจุบัน Firestore SDK สำหรับ iOS ขึ้นอยู่กับโค้ดที่สามารถรับ ไม่เกิน 5 นาทีเพื่อสร้างใน Xcode เพื่อลดเวลาการสร้าง คุณสามารถใช้เวอร์ชันที่คอมไพล์ไว้ล่วงหน้าได้โดยการเพิ่มบรรทัดนี้ลงใน บล็อก target 'Runner' do ใน 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

    แทนที่ IOS_SDK_VERSION ด้วยเวอร์ชันของ Firebase iOS SDK ที่ระบุใน firebase_core firebase_sdk_version.rb หากคุณไม่ได้ใช้เวอร์ชันล่าสุดของ firebase_core มองหาไฟล์นี้ในแพ็กเกจ Pub ในเครื่องของคุณ แคช (โดยปกติคือ ~/.pub-cache)

    นอกจากนี้ ให้ตรวจสอบว่าคุณได้อัปเกรด CocoaPods เป็นเวอร์ชัน 1.9.1 หรือ สูงกว่า:

    gem install cocoapods

    สำหรับข้อมูลเพิ่มเติม โปรดดู ปัญหา ใน GitHub

Java
  1. เพิ่ม Firebase Admin SDK ลงในแอป ดังนี้
    • การใช้ Gradle
      compile 'com.google.firebase:firebase-admin:1.32.0'
      
    • การใช้ Maven
      <dependency>
        <groupId>com.google.firebase</groupId>
        <artifactId>firebase-admin</artifactId>
        <version>1.32.0</version>
      </dependency>
           
  2. ทำตามวิธีการด้านล่างเพื่อเริ่มต้น Cloud Firestore ด้วยข้อมูลเข้าสู่ระบบที่เหมาะสม ในสภาพแวดล้อมของคุณ
Python
  1. เพิ่ม Firebase Admin SDK ไปยังแอป Python โดยทำดังนี้
    pip install --upgrade firebase-admin
  2. ทำตามวิธีการด้านล่างเพื่อเริ่มต้น Cloud Firestore ด้วยข้อมูลเข้าสู่ระบบที่เหมาะสม ในสภาพแวดล้อมของคุณ
C++
  1. ทำตามวิธีการเพื่อ เพิ่ม Firebase ลงในโปรเจ็กต์ C++
  2. อินเทอร์เฟซ C++ สำหรับ Android
    • ทรัพยากร Dependency ของ Gradle เพิ่มรายการต่อไปนี้ลงในโมดูล ไฟล์ Gradle (ระดับแอป) (ปกติราคา 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
              }
              
    • ทรัพยากร Dependency แบบไบนารี ในทำนองเดียวกัน วิธีที่แนะนำในการ ทรัพยากร Dependency แบบไบนารีคือการเพิ่ม ค่าต่อไปนี้ลงใน 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. หากต้องการตั้งค่าการผสานรวมเดสก์ท็อป โปรดดูเพิ่ม Firebase ในโปรเจ็กต์ C++
Unity
  1. ทำตามวิธีการเพื่อ เพิ่ม Firebase ไปยัง Unity โปรเจ็กต์
  2. ใช้อินเทอร์เฟซ Unity เพื่อกำหนดค่าโปรเจ็กต์เพื่อลดบิลด์ Android
  3. คุณต้องลดขนาดบิลด์เพื่อหลีกเลี่ยงข้อความ Error while merging dex archives

    • ตัวเลือกนี้อยู่ในการตั้งค่าโปรแกรมเล่น > Android > การจัดพิมพ์ การตั้งค่า > ลดขนาด
    • ตัวเลือกอาจแตกต่างกันไปตาม Unity เวอร์ชันต่างๆ ดังนั้นให้ดูที่ เอกสารสำหรับ Unity อย่างเป็นทางการ คู่มือแก้ไขข้อบกพร่องบิลด์ของ Firebase Unity
    • หากหลังจากเปิดใช้การลดขนาดแล้ว จำนวนวิธีการอ้างอิงยังคง เกินขีดจำกัด อีกตัวเลือกหนึ่งคือการเปิดใช้ multidex ใน
      • mainTemplate.gradle ถ้าเปิดใช้เทมเพลต Gradle ที่กำหนดเองในส่วนการตั้งค่าโปรแกรมเล่นไว้
      • หรือไฟล์ build.gradle ระดับโมดูล หากคุณใช้ Android Studio เพื่อสร้างโปรเจ็กต์ที่ส่งออก
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. เพิ่มไลบรารี Cloud Firestore PHP ลงในแอปโดยทำดังนี้
    composer require google/cloud-firestore
C#
  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 C# ลงในแอปในไฟล์ .csproj ดังนี้
    <ItemGroup>
      <PackageReference Include="Google.Cloud.Firestore" Version="1.1.0-beta01" />
    </ItemGroup>
  3. เพิ่มโค้ดต่อไปนี้ลงในไฟล์ Program.cs
    using 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. เพิ่มไลบรารี Ruby ใน Cloud Firestore ลงในแอปใน Gemfile:
    gem "google-cloud-firestore"
  3. ติดตั้งการอ้างอิงจาก Gemfile โดยใช้:
    bundle install

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

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

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

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

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

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

เริ่มต้น Cloud Firestore

เริ่มต้นอินสแตนซ์ของ 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);

แทนที่ FIREBASE_CONFIGURATION ด้วยของ firebaseConfig.

หากต้องการคงข้อมูลไว้เมื่ออุปกรณ์ขาดการเชื่อมต่อ โปรดดูเอกสารประกอบเปิดใช้ข้อมูลออฟไลน์

Web

import firebase from "firebase/app";
import "firebase/firestore";

// TODO: Replace the following with your app's Firebase project configuration
// See: https://support.google.com/firebase/answer/7015592
const firebaseConfig = {
    FIREBASE_CONFIGURATION
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);


// Initialize Cloud Firestore and get a reference to the service
const db = firebase.firestore();

แทนที่ FIREBASE_CONFIGURATION ด้วยของ firebaseConfig.

หากต้องการคงข้อมูลไว้เมื่ออุปกรณ์ขาดการเชื่อมต่อ โปรดดูเอกสารประกอบเปิดใช้ข้อมูลออฟไลน์

รวดเร็ว
หมายเหตุ: ผลิตภัณฑ์นี้ใช้ไม่ได้กับเป้าหมาย WatchOS และ App Clip
import FirebaseCore
import FirebaseFirestore
FirebaseApp.configure()

let db = Firestore.firestore()
Objective-C
หมายเหตุ: ผลิตภัณฑ์นี้ใช้ไม่ได้กับเป้าหมาย WatchOS และ App Clip
@import FirebaseCore;
@import FirebaseFirestore;

// Use Firebase library to configure APIs
[FIRApp configure];
  
FIRFirestore *defaultFirestore = [FIRFirestore firestore];

Kotlin+KTX

// Access a Cloud Firestore instance from your Activity
val db = Firebase.firestore

Java

// Access a Cloud Firestore instance from your Activity
FirebaseFirestore db = FirebaseFirestore.getInstance();

Dart

db = FirebaseFirestore.instance;
Java
Cloud Firestore SDK เริ่มต้นในแบบต่างๆ โดยขึ้นอยู่กับ สภาพแวดล้อมของคุณ โดยวิธีการที่ใช้กันมากที่สุดมีดังนี้ เพื่อการอ้างอิงที่สมบูรณ์ ดู เริ่มต้น 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
    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 ในเซิร์ฟเวอร์ของคุณเอง ให้ใช้ บัญชีบริการ

    ไปที่ 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

    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 ในเซิร์ฟเวอร์ของคุณเอง ให้ใช้ บัญชีบริการ

    ไปที่ 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()
  • C++
    // Make sure the call to `Create()` happens some time before you call Firestore::GetInstance().
    App::Create();
    Firestore* db = Firestore::GetInstance();
    Node.js
    Cloud Firestore SDK เริ่มต้นในแบบต่างๆ โดยขึ้นอยู่กับ สภาพแวดล้อมของคุณ โดยวิธีการที่ใช้กันมากที่สุดมีดังนี้ เพื่อการอ้างอิงที่สมบูรณ์ ดู เริ่มต้น 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
    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 ในเซิร์ฟเวอร์ของคุณเอง ให้ใช้ บัญชีบริการ

    ไปที่ 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);
        }
    }
    Unity
    using Firebase.Firestore;
    using Firebase.Extensions;
    FirebaseFirestore db = FirebaseFirestore.DefaultInstance;
    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 สร้างคอลเล็กชันและเอกสารโดยปริยาย ในครั้งแรกที่คุณเพิ่มข้อมูลในเอกสาร คุณไม่จำเป็นต้องระบุ สร้างคอลเล็กชันหรือเอกสารต่างๆ

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

    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
    หมายเหตุ: ผลิตภัณฑ์นี้ใช้ไม่ได้กับเป้าหมาย WatchOS และ 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
    หมายเหตุ: ผลิตภัณฑ์นี้ใช้ไม่ได้กับเป้าหมาย WatchOS และ 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+KTX

    // Create a new user with a first and last name
    val user = hashMapOf(
        "first" to "Ada",
        "last" to "Lovelace",
        "born" to 1815,
    )
    
    // Add a new document with a generated ID
    db.collection("users")
        .add(user)
        .addOnSuccessListener { documentReference ->
            Log.d(TAG, "DocumentSnapshot added with ID: ${documentReference.id}")
        }
        .addOnFailureListener { e ->
            Log.w(TAG, "Error adding document", e)
        }

    Java

    // Create a new user with a first and last name
    Map<String, Object> user = new HashMap<>();
    user.put("first", "Ada");
    user.put("last", "Lovelace");
    user.put("born", 1815);
    
    // Add a new document with a generated ID
    db.collection("users")
            .add(user)
            .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                @Override
                public void onSuccess(DocumentReference documentReference) {
                    Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId());
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.w(TAG, "Error adding document", e);
                }
            });

    Dart

    // Create a new user with a first and last name
    final user = <String, dynamic>{
      "first": "Ada",
      "last": "Lovelace",
      "born": 1815
    };
    
    // Add a new document with a generated ID
    db.collection("users").add(user).then((DocumentReference doc) =>
        print('DocumentSnapshot added with ID: ${doc.id}'));
    Java
    DocumentReference docRef = db.collection("users").document("alovelace");
    // Add document data  with id "alovelace" using a hashmap
    Map<String, Object> data = new HashMap<>();
    data.put("first", "Ada");
    data.put("last", "Lovelace");
    data.put("born", 1815);
    //asynchronously write data
    ApiFuture<WriteResult> result = docRef.set(data);
    // ...
    // result.get() blocks on response
    System.out.println("Update time : " + result.get().getUpdateTime());
    Python
    doc_ref = db.collection("users").document("alovelace")
    doc_ref.set({"first": "Ada", "last": "Lovelace", "born": 1815})

    Python

    doc_ref = db.collection("users").document("alovelace")
    await doc_ref.set({"first": "Ada", "last": "Lovelace", "born": 1815})
    C++
    // Add a new document with a generated ID
    Future<DocumentReference> user_ref =
        db->Collection("users").Add({{"first", FieldValue::String("Ada")},
                                     {"last", FieldValue::String("Lovelace")},
                                     {"born", FieldValue::Integer(1815)}});
    
    user_ref.OnCompletion([](const Future<DocumentReference>& future) {
      if (future.error() == Error::kErrorOk) {
        std::cout << "DocumentSnapshot added with ID: " << future.result()->id()
                  << std::endl;
      } else {
        std::cout << "Error adding document: " << future.error_message() << std::endl;
      }
    });
    Node.js
    const docRef = db.collection('users').doc('alovelace');
    
    await docRef.set({
      first: 'Ada',
      last: 'Lovelace',
      born: 1815
    });
    Go
    _, _, err := client.Collection("users").Add(ctx, map[string]interface{}{
    	"first": "Ada",
    	"last":  "Lovelace",
    	"born":  1815,
    })
    if err != nil {
    	log.Fatalf("Failed adding alovelace: %v", err)
    }
    PHP

    PHP

    โปรดดูข้อมูลเพิ่มเติมเกี่ยวกับการติดตั้งและสร้างไคลเอ็นต์ Cloud Firestore ที่ ไลบรารีของไคลเอ็นต์ 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."

    ตอนนี้ให้เพิ่มเอกสารอื่นในคอลเล็กชัน users โปรดสังเกตว่าเอกสารนี้ มีคู่คีย์-ค่า (ชื่อกลาง) ที่ไม่แสดงในส่วนแรก เอกสาร เอกสารในคอลเล็กชันอาจมีชุดข้อมูลที่แตกต่างกัน

    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
    หมายเหตุ: ผลิตภัณฑ์นี้ใช้ไม่ได้กับเป้าหมาย WatchOS และ 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
    หมายเหตุ: ผลิตภัณฑ์นี้ใช้ไม่ได้กับเป้าหมาย WatchOS และ 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+KTX

    // Create a new user with a first, middle, and last name
    val user = hashMapOf(
        "first" to "Alan",
        "middle" to "Mathison",
        "last" to "Turing",
        "born" to 1912,
    )
    
    // Add a new document with a generated ID
    db.collection("users")
        .add(user)
        .addOnSuccessListener { documentReference ->
            Log.d(TAG, "DocumentSnapshot added with ID: ${documentReference.id}")
        }
        .addOnFailureListener { e ->
            Log.w(TAG, "Error adding document", e)
        }

    Java

    // Create a new user with a first, middle, and last name
    Map<String, Object> user = new HashMap<>();
    user.put("first", "Alan");
    user.put("middle", "Mathison");
    user.put("last", "Turing");
    user.put("born", 1912);
    
    // Add a new document with a generated ID
    db.collection("users")
            .add(user)
            .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                @Override
                public void onSuccess(DocumentReference documentReference) {
                    Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId());
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.w(TAG, "Error adding document", e);
                }
            });

    Dart

    // Create a new user with a first and last name
    final user = <String, dynamic>{
      "first": "Alan",
      "middle": "Mathison",
      "last": "Turing",
      "born": 1912
    };
    
    // Add a new document with a generated ID
    db.collection("users").add(user).then((DocumentReference doc) =>
        print('DocumentSnapshot added with ID: ${doc.id}'));
    Java
    DocumentReference docRef = db.collection("users").document("aturing");
    // Add document data with an additional field ("middle")
    Map<String, Object> data = new HashMap<>();
    data.put("first", "Alan");
    data.put("middle", "Mathison");
    data.put("last", "Turing");
    data.put("born", 1912);
    
    ApiFuture<WriteResult> result = docRef.set(data);
    System.out.println("Update time : " + result.get().getUpdateTime());
    Python
    doc_ref = db.collection("users").document("aturing")
    doc_ref.set({"first": "Alan", "middle": "Mathison", "last": "Turing", "born": 1912})

    Python

    doc_ref = db.collection("users").document("aturing")
    await doc_ref.set(
        {"first": "Alan", "middle": "Mathison", "last": "Turing", "born": 1912}
    )
    C++
    db->Collection("users")
        .Add({{"first", FieldValue::String("Alan")},
              {"middle", FieldValue::String("Mathison")},
              {"last", FieldValue::String("Turing")},
              {"born", FieldValue::Integer(1912)}})
        .OnCompletion([](const Future<DocumentReference>& future) {
          if (future.error() == Error::kErrorOk) {
            std::cout << "DocumentSnapshot added with ID: "
                      << future.result()->id() << std::endl;
          } else {
            std::cout << "Error adding document: " << future.error_message()
                      << std::endl;
          }
        });
    Node.js
    const aTuringRef = db.collection('users').doc('aturing');
    
    await aTuringRef.set({
      'first': 'Alan',
      'middle': 'Mathison',
      'last': 'Turing',
      'born': 1912
    });
    Go
    _, _, err = client.Collection("users").Add(ctx, map[string]interface{}{
    	"first":  "Alan",
    	"middle": "Mathison",
    	"last":   "Turing",
    	"born":   1912,
    })
    if err != nil {
    	log.Fatalf("Failed adding aturing: %v", err)
    }
    PHP

    PHP

    โปรดดูข้อมูลเพิ่มเติมเกี่ยวกับการติดตั้งและสร้างไคลเอ็นต์ Cloud Firestore ที่ ไลบรารีของไคลเอ็นต์ 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."

    อ่านข้อมูล

    ใช้ข้อมูล ผู้ชมใน คอนโซล Firebase เพื่อยืนยันว่าคุณได้เพิ่มข้อมูลลงใน Cloud Firestore อย่างรวดเร็วแล้ว

    คุณยังสามารถใช้ปุ่ม "get" เพื่อเรียกข้อมูลคอลเล็กชันทั้งหมด

    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
    หมายเหตุ: ผลิตภัณฑ์นี้ใช้ไม่ได้กับเป้าหมาย WatchOS และ 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
    หมายเหตุ: ผลิตภัณฑ์นี้ใช้ไม่ได้กับเป้าหมาย WatchOS และ 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+KTX

    db.collection("users")
        .get()
        .addOnSuccessListener { result ->
            for (document in result) {
                Log.d(TAG, "${document.id} => ${document.data}")
            }
        }
        .addOnFailureListener { exception ->
            Log.w(TAG, "Error getting documents.", exception)
        }

    Java

    db.collection("users")
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (task.isSuccessful()) {
                        for (QueryDocumentSnapshot document : task.getResult()) {
                            Log.d(TAG, document.getId() + " => " + document.getData());
                        }
                    } else {
                        Log.w(TAG, "Error getting documents.", task.getException());
                    }
                }
            });

    Dart

    await db.collection("users").get().then((event) {
      for (var doc in event.docs) {
        print("${doc.id} => ${doc.data()}");
      }
    });
    Java
    // asynchronously retrieve all users
    ApiFuture<QuerySnapshot> query = db.collection("users").get();
    // ...
    // query.get() blocks on response
    QuerySnapshot querySnapshot = query.get();
    List<QueryDocumentSnapshot> documents = querySnapshot.getDocuments();
    for (QueryDocumentSnapshot document : documents) {
      System.out.println("User: " + document.getId());
      System.out.println("First: " + document.getString("first"));
      if (document.contains("middle")) {
        System.out.println("Middle: " + document.getString("middle"));
      }
      System.out.println("Last: " + document.getString("last"));
      System.out.println("Born: " + document.getLong("born"));
    }
    Python
    users_ref = db.collection("users")
    docs = users_ref.stream()
    
    for doc in docs:
        print(f"{doc.id} => {doc.to_dict()}")

    Python

    users_ref = db.collection("users")
    docs = users_ref.stream()
    
    async for doc in docs:
        print(f"{doc.id} => {doc.to_dict()}")
    C++
    Future<QuerySnapshot> users = db->Collection("users").Get();
    users.OnCompletion([](const Future<QuerySnapshot>& future) {
      if (future.error() == Error::kErrorOk) {
        for (const DocumentSnapshot& document : future.result()->documents()) {
          std::cout << document << std::endl;
        }
      } else {
        std::cout << "Error getting documents: " << future.error_message()
                  << std::endl;
      }
    });
    Node.js
    const snapshot = await db.collection('users').get();
    snapshot.forEach((doc) => {
      console.log(doc.id, '=>', doc.data());
    });
    Go
    iter := client.Collection("users").Documents(ctx)
    for {
    	doc, err := iter.Next()
    	if err == iterator.Done {
    		break
    	}
    	if err != nil {
    		log.Fatalf("Failed to iterate: %v", err)
    	}
    	fmt.Println(doc.Data())
    }
    PHP

    PHP

    โปรดดูข้อมูลเพิ่มเติมเกี่ยวกับการติดตั้งและสร้างไคลเอ็นต์ Cloud Firestore ที่ ไลบรารีของไคลเอ็นต์ 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

    รักษาความปลอดภัยให้ข้อมูลของคุณ

    หากคุณใช้ SDK สำหรับแพลตฟอร์มเว็บ, Android หรือ Apple ให้ใช้ Firebase การตรวจสอบสิทธิ์และ กฎความปลอดภัยของ Cloud Firestore เพื่อรักษาความปลอดภัยให้ข้อมูล Cloud Firestore

    ชุดกฎพื้นฐานที่คุณสามารถใช้เพื่อเริ่มต้นได้มีดังนี้ คุณสามารถแก้ไข กฎความปลอดภัยในกฎ แท็บ จาก คอนโซล

    ต้องมีการตรวจสอบสิทธิ์

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

    โหมดล็อกขณะคุมสอบ

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

    โปรดทำตามขั้นตอนต่างๆ ก่อนที่จะทำให้แอปบนเว็บ, Android หรือ iOS ใช้งานได้เป็นเวอร์ชันที่ใช้งานจริง เพื่อให้แน่ใจว่ามีเพียงไคลเอ็นต์ของแอปเท่านั้นที่จะเข้าถึงข้อมูล Cloud Firestore ได้ ดูเอกสารประกอบเกี่ยวกับ App Check

    หากคุณใช้ SDK ของเซิร์ฟเวอร์อันใดอันหนึ่ง ให้ใช้ Identity and Access Management (IAM) เพื่อรักษาความปลอดภัยของข้อมูล ใน Cloud Firestore

    ดูวิดีโอบทแนะนำ

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

    เว็บ
    iOS ขึ้นไป
    Android

    ค้นหาวิดีโอเพิ่มเติมได้ใน Firebase ช่อง YouTube

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

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

    • Codelabs — ดูวิธีใช้ Cloud Firestore ในแอปจริงโดย จาก Codelab สำหรับ Android, iOS หรือ เว็บ
    • โมเดลข้อมูล — ดูข้อมูลเพิ่มเติมเกี่ยวกับวิธีที่ข้อมูล ที่มีโครงสร้างใน Cloud Firestore รวมถึงข้อมูลตามลำดับชั้นและคอลเล็กชันย่อย
    • เพิ่มข้อมูล — ดูข้อมูลเพิ่มเติมเกี่ยวกับการสร้างและอัปเดตข้อมูลใน Cloud Firestore
    • รับข้อมูล — ดูข้อมูลเพิ่มเติมเกี่ยวกับวิธีดึงข้อมูล
    • ค้นหาแบบง่ายและแบบผสม — ดูวิธีเรียกใช้การค้นหาแบบง่ายและแบบผสม
    • สั่งซื้อและจำกัดการค้นหา ดูวิธีสั่งซื้อ และจำกัดข้อมูลที่แสดงผลจากการค้นหา