Catch up on highlights from Firebase at Google I/O 2023. Learn more

เริ่มต้นใช้งาน 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 ให้เลือกโหมดล็อก

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

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

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

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

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

ตั้งค่าสภาพแวดล้อมการพัฒนาของคุณ

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

Web version 8

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

Web version 9

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

ทำตามคำแนะนำเพื่อ เพิ่ม Firebase ในแอป Apple

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

  1. ใน Xcode เมื่อโปรเจ็กต์แอปของคุณเปิดอยู่ ให้ไปที่ File > Swift Packages > Add Package Dependency
  2. เมื่อได้รับแจ้ง ให้เพิ่มที่เก็บ Firebase Apple platforms SDK:
  3.   https://github.com/firebase/firebase-ios-sdk
      
  4. เลือกห้องสมุด Firestore
  5. เมื่อเสร็จแล้ว Xcode จะเริ่มแก้ไขและดาวน์โหลดการอ้างอิงของคุณโดยอัตโนมัติในเบื้องหลัง

Kotlin+KTX

  1. ทำตามคำแนะนำเพื่อ เพิ่ม Firebase ในแอป Android
  2. ใช้ Firebase Android BoM ประกาศการพึ่งพาสำหรับไลบรารี Cloud Firestore Android ใน โมดูลของคุณ (ระดับแอป) ไฟล์ Gradle (โดยปกติคือ app/build.gradle )
    dependencies {
        // Import the BoM for the Firebase platform
        implementation platform('com.google.firebase:firebase-bom:32.1.0')
    
        // Declare the dependency for the Cloud Firestore library
        // When using the BoM, you don't specify versions in Firebase library dependencies
        implementation 'com.google.firebase:firebase-firestore-ktx'
    }
    

    เมื่อใช้ Firebase Android BoM แอปของคุณจะใช้ไลบรารี Firebase Android เวอร์ชันที่เข้ากันได้เสมอ

    (ทางเลือก) ประกาศการอ้างอิงไลบรารี Firebase โดยไม่ ใช้ BoM

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

    โปรดทราบว่าหากคุณใช้ไลบรารี 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-ktx:24.6.1'
    }
    

Java

  1. ทำตามคำแนะนำเพื่อ เพิ่ม Firebase ในแอป Android
  2. ใช้ Firebase Android BoM ประกาศการพึ่งพาสำหรับไลบรารี Cloud Firestore Android ใน โมดูลของคุณ (ระดับแอป) ไฟล์ Gradle (โดยปกติคือ app/build.gradle )
    dependencies {
        // Import the BoM for the Firebase platform
        implementation platform('com.google.firebase:firebase-bom:32.1.0')
    
        // Declare the dependency for the Cloud Firestore library
        // When using the BoM, you don't specify versions in Firebase library dependencies
        implementation 'com.google.firebase:firebase-firestore'
    }
    

    เมื่อใช้ Firebase Android BoM แอปของคุณจะใช้ไลบรารี Firebase Android เวอร์ชันที่เข้ากันได้เสมอ

    (ทางเลือก) ประกาศการอ้างอิงไลบรารี Firebase โดยไม่ ใช้ BoM

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

    โปรดทราบว่าหากคุณใช้ไลบรารี 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:24.6.1'
    }
    

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
      pod 'FirebaseFirestore', :git => 'https://github.com/invertase/firestore-ios-sdk-frameworks.git', :tag => '8.15.0'
      # ...
    end

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

    gem install cocoapods

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

ชวา
  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 ด้วยข้อมูลรับรองที่เหมาะสมในสภาพแวดล้อมของคุณ
หลาม
  1. เพิ่ม Firebase Admin SDK ลงในแอป Python ของคุณ:
    pip install --upgrade firebase-admin
  2. ทำตามคำแนะนำด้านล่างเพื่อเริ่มต้น Cloud Firestore ด้วยข้อมูลรับรองที่เหมาะสมในสภาพแวดล้อมของคุณ
ภาษาซี++
  1. ทำตามคำแนะนำเพื่อ เพิ่ม Firebase ในโครงการ C++ ของคุณ
  2. อินเทอร์เฟซ C ++ สำหรับ Android
    • การพึ่งพา 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
              }
              
    • การพึ่งพาไบนารี วิธีที่แนะนำในการรับการขึ้นต่อกันแบบไบนารีคือการเพิ่มสิ่งต่อไปนี้ในไฟล์ 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++ ของคุณ
ความสามัคคี
  1. ทำตามคำแนะนำเพื่อ เพิ่ม Firebase ในโครงการ Unity ของคุณ
  2. อินเทอร์เฟซ Unity สำหรับ Android
  3. เมื่อสร้างสำหรับ Android ให้เปิดใช้งาน ProGuarding เพื่อหลีกเลี่ยงขีดจำกัดของ Android DEX ในการทำเช่นนั้น ในโปรแกรมแก้ไข Unity:

    1. เลือก ไฟล์ > การตั้งค่าการสร้าง
    2. เปลี่ยน 'แพลตฟอร์ม' เป็น 'Android' และคลิก 'เปลี่ยนแพลตฟอร์ม'
    3. คลิก 'การตั้งค่าผู้เล่น…'
    4. ใน Unity UI หลัก ภายใต้ 'การตั้งค่าสำหรับ Android' เลือก 'การตั้งค่าการเผยแพร่'
    5. ในส่วน 'ย่อขนาด' ให้เปลี่ยนทั้งการตั้งค่ารีลีสและดีบักจาก 'ไม่มี' เป็น 'ProGuard'
โหนด js
  1. เพิ่ม Firebase Admin SDK ในแอปของคุณ:
    npm install firebase-admin --save
  2. ทำตามคำแนะนำด้านล่างเพื่อเริ่มต้น Cloud Firestore ด้วยข้อมูลรับรองที่เหมาะสมในสภาพแวดล้อมของคุณ
ไป
  1. เพิ่ม SDK ผู้ดูแลระบบ Firebase ลงในแอป Go:
    go get firebase.google.com/go
    
  2. ทำตามคำแนะนำด้านล่างเพื่อเริ่มต้น Cloud Firestore ด้วยข้อมูลรับรองที่เหมาะสมในสภาพแวดล้อมของคุณ
พี.เอช.พี
  1. ไลบรารีไคลเอ็นต์ของเซิร์ฟเวอร์ Cloud Firestore (Java, Node.js, Python, Go, PHP, C# และ Ruby) ใช้ Google Application Default Credentials สำหรับการตรวจสอบสิทธิ์
    • หากต้องการตรวจสอบสิทธิ์จากสภาพแวดล้อมการพัฒนาของคุณ ให้ตั้งค่าตัวแปรสภาพแวดล้อม 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
ค#
  1. ไลบรารีไคลเอ็นต์ของเซิร์ฟเวอร์ Cloud Firestore (Java, Node.js, Python, Go, PHP, C# และ Ruby) ใช้ Google Application Default Credentials สำหรับการตรวจสอบสิทธิ์
    • หากต้องการตรวจสอบสิทธิ์จากสภาพแวดล้อมการพัฒนาของคุณ ให้ตั้งค่าตัวแปรสภาพแวดล้อม 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;
ทับทิม
  1. ไลบรารีไคลเอ็นต์ของเซิร์ฟเวอร์ Cloud Firestore (Java, Node.js, Python, Go, PHP, C# และ Ruby) ใช้ Google Application Default Credentials สำหรับการตรวจสอบสิทธิ์
    • หากต้องการตรวจสอบสิทธิ์จากสภาพแวดล้อมการพัฒนาของคุณ ให้ตั้งค่าตัวแปรสภาพแวดล้อม 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. ติดตั้งการอ้างอิงจาก 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:

Web version 9

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 version 8

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()
วัตถุประสงค์-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;
ชวา
Cloud Firestore SDK เริ่มต้นได้หลายวิธีขึ้นอยู่กับสภาพแวดล้อมของคุณ ด้านล่างนี้เป็นวิธีการทั่วไป สำหรับข้อมูลอ้างอิงทั้งหมด โปรดดู Initialize the 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 & admin > บัญชีบริการ ใน Google Cloud Console สร้างคีย์ส่วนตัวใหม่และบันทึกไฟล์ 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();
    
  • หลาม
    Cloud Firestore SDK เริ่มต้นได้หลายวิธีขึ้นอยู่กับสภาพแวดล้อมของคุณ ด้านล่างนี้เป็นวิธีการทั่วไป สำหรับข้อมูลอ้างอิงทั้งหมด โปรดดู Initialize the 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 & admin > บัญชีบริการ ใน Google Cloud Console สร้างคีย์ส่วนตัวใหม่และบันทึกไฟล์ 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 เริ่มต้นได้หลายวิธีขึ้นอยู่กับสภาพแวดล้อมของคุณ ด้านล่างนี้เป็นวิธีการทั่วไป สำหรับข้อมูลอ้างอิงทั้งหมด โปรดดู Initialize the 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 & admin > บัญชีบริการ ใน Google Cloud Console สร้างคีย์ส่วนตัวใหม่และบันทึกไฟล์ 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()
  • ภาษาซี++
    // Make sure the call to `Create()` happens some time before you call Firestore::GetInstance().
    App::Create();
    Firestore* db = Firestore::GetInstance();
    โหนด js
    Cloud Firestore SDK เริ่มต้นได้หลายวิธีขึ้นอยู่กับสภาพแวดล้อมของคุณ ด้านล่างนี้เป็นวิธีการทั่วไป สำหรับข้อมูลอ้างอิงทั้งหมด โปรดดู Initialize the Admin SDK
    • เริ่มต้นบนฟังก์ชั่นคลาวด์
      const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
      const { getFirestore, Timestamp, FieldValue } = require('firebase-admin/firestore');
      initializeApp();
      
      const db = getFirestore();
      
    • เริ่มต้นบน Google Cloud
      const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
      const { getFirestore, Timestamp, FieldValue } = require('firebase-admin/firestore');
      initializeApp({
        credential: applicationDefault()
      });
      
      const db = getFirestore();
    • เริ่มต้นบนเซิร์ฟเวอร์ของคุณเอง

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

      const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
      const { getFirestore, Timestamp, FieldValue } = require('firebase-admin/firestore');
      const serviceAccount = require('./path/to/serviceAccountKey.json');
      
      initializeApp({
        credential: cert(serviceAccount)
      });
      
      const db = getFirestore();
      
    ไป
    Cloud Firestore SDK เริ่มต้นได้หลายวิธีขึ้นอยู่กับสภาพแวดล้อมของคุณ ด้านล่างนี้เป็นวิธีการทั่วไป สำหรับข้อมูลอ้างอิงทั้งหมด โปรดดู Initialize the 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 & admin > บัญชีบริการ ใน Google Cloud Console สร้างคีย์ส่วนตัวใหม่และบันทึกไฟล์ 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()
    
  • พี.เอช.พี

    พี.เอช.พี

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

    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);
        }
    }
    ความสามัคคี
    using Firebase.Firestore;
    using Firebase.Extensions;
    FirebaseFirestore db = FirebaseFirestore.DefaultInstance;
    ค#

    ค#

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

    FirestoreDb db = FirestoreDb.Create(project);
    Console.WriteLine("Created Cloud Firestore client with project ID: {0}", project);
    ทับทิม
    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 version 9

    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 version 8

    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);
    });
    สวิฟต์
    หมายเหตุ: ผลิตภัณฑ์นี้ไม่พร้อมใช้งานบนเป้าหมาย watchOS และ App Clip
    // Add a new document with a generated ID
    var ref: DocumentReference? = nil
    ref = db.collection("users").addDocument(data: [
        "first": "Ada",
        "last": "Lovelace",
        "born": 1815
    ]) { err in
        if let err = err {
            print("Error adding document: \(err)")
        } else {
            print("Document added with ID: \(ref!.documentID)")
        }
    }
    วัตถุประสงค์-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}'));
    ชวา
    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());
    หลาม
    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})
    ภาษาซี++
    // 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;
      }
    });
    โหนด js
    const docRef = db.collection('users').doc('alovelace');
    
    await docRef.set({
      first: 'Ada',
      last: 'Lovelace',
      born: 1815
    });
    ไป
    _, _, 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)
    }
    พี.เอช.พี

    พี.เอช.พี

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

    $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);
    ความสามัคคี
    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.");
    });
    ค#
    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);
    ทับทิม
    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 version 9

    // 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 version 8

    // 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);
    });
    สวิฟต์
    หมายเหตุ: ผลิตภัณฑ์นี้ไม่พร้อมใช้งานบนเป้าหมาย watchOS และ App Clip
    // Add a second document with a generated ID.
    ref = db.collection("users").addDocument(data: [
        "first": "Alan",
        "middle": "Mathison",
        "last": "Turing",
        "born": 1912
    ]) { err in
        if let err = err {
            print("Error adding document: \(err)")
        } else {
            print("Document added with ID: \(ref!.documentID)")
        }
    }
    วัตถุประสงค์-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}'));
    ชวา
    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());
    หลาม
    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}
    )
    ภาษาซี++
    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;
          }
        });
    โหนด js
    const aTuringRef = db.collection('users').doc('aturing');
    
    await aTuringRef.set({
      'first': 'Alan',
      'middle': 'Mathison',
      'last': 'Turing',
      'born': 1912
    });
    ไป
    _, _, 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)
    }
    พี.เอช.พี

    พี.เอช.พี

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

    $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);
    ความสามัคคี
    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.");
    });
    ค#
    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);
    ทับทิม
    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 แล้ว

    คุณยังสามารถใช้เมธอด "รับ" เพื่อดึงคอลเล็กชันทั้งหมด

    Web version 9

    import { collection, getDocs } from "firebase/firestore"; 
    
    const querySnapshot = await getDocs(collection(db, "users"));
    querySnapshot.forEach((doc) => {
      console.log(`${doc.id} => ${doc.data()}`);
    });

    Web version 8

    db.collection("users").get().then((querySnapshot) => {
        querySnapshot.forEach((doc) => {
            console.log(`${doc.id} => ${doc.data()}`);
        });
    });
    สวิฟต์
    หมายเหตุ: ผลิตภัณฑ์นี้ไม่พร้อมใช้งานบนเป้าหมาย watchOS และ App Clip
    db.collection("users").getDocuments() { (querySnapshot, err) in
        if let err = err {
            print("Error getting documents: \(err)")
        } else {
            for document in querySnapshot!.documents {
                print("\(document.documentID) => \(document.data())")
            }
        }
    }
    วัตถุประสงค์-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()}");
      }
    });
    ชวา
    // 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"));
    }
    หลาม
    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()}")
    ภาษาซี++
    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;
      }
    });
    โหนด js
    const snapshot = await db.collection('users').get();
    snapshot.forEach((doc) => {
      console.log(doc.id, '=>', doc.data());
    });
    ไป
    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())
    }
    พี.เอช.พี

    พี.เอช.พี

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

    $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);
    ความสามัคคี
    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.");
    });
    ค#
    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();
    }
    ทับทิม
    users_ref = firestore.col collection_path
    users_ref.get do |user|
      puts "#{user.document_id} data: #{user.data}."
    end

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

    หากคุณใช้ SDK ของแพลตฟอร์มเว็บ, Android หรือ Apple ให้ใช้ Firebase Authentication และ Cloud Firestore Security Rules เพื่อรักษาความปลอดภัยข้อมูลของคุณใน Cloud Firestore

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

    จำเป็นต้องมีการตรวจสอบสิทธิ์

    // Allow read/write access on all documents to any user signed in to the application
    service cloud.firestore {
      match /databases/{database}/documents {
        match /{document=**} {
          allow read, write: if request.auth != null;
        }
      }
    }
    

    โหมดล็อค

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

    โหมดทดสอบ

    // Allow read/write access to all users under any conditions
    // Warning: **NEVER** use this rule set in production; it allows
    // anyone to overwrite your entire database.
    service cloud.firestore {
      match /databases/{database}/documents {
        match /{document=**} {
          allow read, write: if true;
        }
      }
    }
    

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

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

    ดูวิดีโอสอน

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

    เว็บ
    iOS+
    แอนดรอยด์

    คุณสามารถค้นหาวิดีโอเพิ่มเติมได้ใน ช่อง YouTube ของ Firebase

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

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