क्लाउड फायरस्टोर से डेटा प्राप्त करें

क्लाउड फायरस्टोर में संग्रहीत डेटा को पुनः प्राप्त करने के तीन तरीके हैं। इनमें से किसी भी विधि का उपयोग दस्तावेज़ों, दस्तावेज़ों के संग्रह या प्रश्नों के परिणामों के साथ किया जा सकता है:

  • डेटा प्राप्त करने के लिए एक बार विधि को कॉल करें।
  • डेटा-परिवर्तन ईवेंट प्राप्त करने के लिए श्रोता सेट करें।
  • डेटा बंडलों के माध्यम से बाहरी स्रोत से फायरस्टोर स्नैपशॉट डेटा को बल्क-लोड करें। अधिक विवरण के लिए बंडल दस्तावेज़ देखें।

जब आप श्रोता सेट करते हैं, तो क्लाउड फायरस्टोर आपके श्रोता को डेटा का प्रारंभिक स्नैपशॉट भेजता है, और फिर हर बार दस्तावेज़ बदलने पर एक और स्नैपशॉट भेजता है।

शुरू करने से पहले

क्लाउड फायरस्टोर डेटाबेस बनाने के लिए क्लाउड फायरस्टोर के साथ शुरुआत करें देखें।

क्लाउड फायरस्टोर प्रारंभ करें

क्लाउड फायरस्टोर का एक उदाहरण प्रारंभ करें:

Web modular API

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 namespaced API

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 से बदलें।

जब डिवाइस अपना कनेक्शन खो देता है तो डेटा को बनाए रखने के लिए, ऑफ़लाइन डेटा सक्षम करें दस्तावेज़ देखें।

तीव्र
नोट: यह उत्पाद वॉचओएस और ऐप क्लिप लक्ष्य पर उपलब्ध नहीं है।
import FirebaseCore
import FirebaseFirestore
FirebaseApp.configure()

let db = Firestore.firestore()
उद्देश्य सी
नोट: यह उत्पाद वॉचओएस और ऐप क्लिप लक्ष्य पर उपलब्ध नहीं है।
@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;
जावा
क्लाउड फायरस्टोर एसडीके को आपके परिवेश के आधार पर अलग-अलग तरीकों से आरंभ किया गया है। नीचे सबसे सामान्य तरीके दिए गए हैं. संपूर्ण संदर्भ के लिए, एडमिन एसडीके को प्रारंभ करें देखें।
  • Google क्लाउड
    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();
    
    पर प्रारंभ करें
  • अपने सर्वर पर प्रारंभ करें

    अपने स्वयं के सर्वर पर फायरबेस एडमिन एसडीके का उपयोग करने के लिए, एक सेवा खाते का उपयोग करें।

    Google क्लाउड कंसोल में IAM और एडमिन > सेवा खाते पर जाएँ। एक नई निजी कुंजी बनाएं और JSON फ़ाइल सहेजें। फिर SDK को प्रारंभ करने के लिए फ़ाइल का उपयोग करें:

    import com.google.auth.oauth2.GoogleCredentials;
    import com.google.cloud.firestore.Firestore;
    
    import com.google.firebase.FirebaseApp;
    import com.google.firebase.FirebaseOptions;
    
    // Use a service account
    InputStream serviceAccount = new FileInputStream("path/to/serviceAccount.json");
    GoogleCredentials credentials = GoogleCredentials.fromStream(serviceAccount);
    FirebaseOptions options = new FirebaseOptions.Builder()
        .setCredentials(credentials)
        .build();
    FirebaseApp.initializeApp(options);
    
    Firestore db = FirestoreClient.getFirestore();
    
  • अजगर
    क्लाउड फायरस्टोर एसडीके को आपके परिवेश के आधार पर अलग-अलग तरीकों से आरंभ किया गया है। नीचे सबसे सामान्य तरीके दिए गए हैं. संपूर्ण संदर्भ के लिए, एडमिन एसडीके को प्रारंभ करें देखें।
  • Google क्लाउड
    import firebase_admin
    from firebase_admin import firestore
    
    # Application Default credentials are automatically created.
    app = firebase_admin.initialize_app()
    db = firestore.client()
    पर प्रारंभ करें

    एसडीके को आरंभ करने के लिए मौजूदा एप्लिकेशन डिफ़ॉल्ट क्रेडेंशियल का भी उपयोग किया जा सकता है।

    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()
  • अपने सर्वर पर प्रारंभ करें

    अपने स्वयं के सर्वर पर फायरबेस एडमिन एसडीके का उपयोग करने के लिए, एक सेवा खाते का उपयोग करें।

    Google क्लाउड कंसोल में IAM और एडमिन > सेवा खाते पर जाएँ। एक नई निजी कुंजी बनाएं और JSON फ़ाइल सहेजें। फिर SDK को प्रारंभ करने के लिए फ़ाइल का उपयोग करें:

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

    क्लाउड फायरस्टोर एसडीके को आपके परिवेश के आधार पर अलग-अलग तरीकों से आरंभ किया गया है। नीचे सबसे सामान्य तरीके दिए गए हैं. संपूर्ण संदर्भ के लिए, एडमिन एसडीके को प्रारंभ करें देखें।
  • Google क्लाउड
    import firebase_admin
    from firebase_admin import firestore_async
    
    # Application Default credentials are automatically created.
    app = firebase_admin.initialize_app()
    db = firestore_async.client()
    पर प्रारंभ करें

    एसडीके को आरंभ करने के लिए मौजूदा एप्लिकेशन डिफ़ॉल्ट क्रेडेंशियल का भी उपयोग किया जा सकता है।

    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()
  • अपने सर्वर पर प्रारंभ करें

    अपने स्वयं के सर्वर पर फायरबेस एडमिन एसडीके का उपयोग करने के लिए, एक सेवा खाते का उपयोग करें।

    Google क्लाउड कंसोल में IAM और एडमिन > सेवा खाते पर जाएँ। एक नई निजी कुंजी बनाएं और JSON फ़ाइल सहेजें। फिर SDK को प्रारंभ करने के लिए फ़ाइल का उपयोग करें:

    import firebase_admin
    from firebase_admin import credentials
    from firebase_admin import firestore_async
    
    # Use a service account.
    cred = credentials.Certificate('path/to/serviceAccount.json')
    
    app = firebase_admin.initialize_app(cred)
    
    db = firestore_async.client()
  • सी++
    // Make sure the call to `Create()` happens some time before you call Firestore::GetInstance().
    App::Create();
    Firestore* db = Firestore::GetInstance();
    नोड.जे.एस
    क्लाउड फायरस्टोर एसडीके को आपके परिवेश के आधार पर अलग-अलग तरीकों से आरंभ किया गया है। नीचे सबसे सामान्य तरीके दिए गए हैं. संपूर्ण संदर्भ के लिए, एडमिन एसडीके को प्रारंभ करें देखें।
    • क्लाउड फ़ंक्शंस
      const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
      const { getFirestore, Timestamp, FieldValue, Filter } = require('firebase-admin/firestore');
      initializeApp();
      
      const db = getFirestore();
      
      पर प्रारंभ करें
    • Google क्लाउड पर आरंभ करें
      const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
      const { getFirestore, Timestamp, FieldValue, Filter } = require('firebase-admin/firestore');
      initializeApp({
        credential: applicationDefault()
      });
      
      const db = getFirestore();
    • अपने सर्वर पर प्रारंभ करें

      अपने स्वयं के सर्वर (या किसी अन्य Node.js वातावरण) पर फायरबेस एडमिन SDK का उपयोग करने के लिए, एक सेवा खाते का उपयोग करें। Google क्लाउड कंसोल में IAM और एडमिन > सेवा खाते पर जाएँ। एक नई निजी कुंजी बनाएं और JSON फ़ाइल सहेजें। फिर SDK को प्रारंभ करने के लिए फ़ाइल का उपयोग करें:

      const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
      const { getFirestore, Timestamp, FieldValue, Filter } = require('firebase-admin/firestore');
      const serviceAccount = require('./path/to/serviceAccountKey.json');
      
      initializeApp({
        credential: cert(serviceAccount)
      });
      
      const db = getFirestore();
      
    जाना
    क्लाउड फायरस्टोर एसडीके को आपके परिवेश के आधार पर अलग-अलग तरीकों से आरंभ किया गया है। नीचे सबसे सामान्य तरीके दिए गए हैं. संपूर्ण संदर्भ के लिए, एडमिन एसडीके को प्रारंभ करें देखें।
  • Google क्लाउड
    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()
    
    पर प्रारंभ करें
  • अपने सर्वर पर प्रारंभ करें

    अपने स्वयं के सर्वर पर फायरबेस एडमिन एसडीके का उपयोग करने के लिए, एक सेवा खाते का उपयोग करें।

    Google क्लाउड कंसोल में IAM और एडमिन > सेवा खाते पर जाएँ। एक नई निजी कुंजी बनाएं और JSON फ़ाइल सहेजें। फिर SDK को प्रारंभ करने के लिए फ़ाइल का उपयोग करें:

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

    पीएचपी

    क्लाउड फायरस्टोर क्लाइंट स्थापित करने और बनाने के बारे में अधिक जानकारी के लिए, क्लाउड फायरस्टोर क्लाइंट लाइब्रेरीज़ देखें।

    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;
    सी#

    सी#

    क्लाउड फायरस्टोर क्लाइंट स्थापित करने और बनाने के बारे में अधिक जानकारी के लिए, क्लाउड फायरस्टोर क्लाइंट लाइब्रेरीज़ देखें।

    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."

    उदाहरण डेटा

    आरंभ करने के लिए, शहरों के बारे में कुछ डेटा लिखें ताकि हम इसे वापस पढ़ने के विभिन्न तरीकों पर गौर कर सकें:

    Web modular API

    import { collection, doc, setDoc } from "firebase/firestore"; 
    
    const citiesRef = collection(db, "cities");
    
    await setDoc(doc(citiesRef, "SF"), {
        name: "San Francisco", state: "CA", country: "USA",
        capital: false, population: 860000,
        regions: ["west_coast", "norcal"] });
    await setDoc(doc(citiesRef, "LA"), {
        name: "Los Angeles", state: "CA", country: "USA",
        capital: false, population: 3900000,
        regions: ["west_coast", "socal"] });
    await setDoc(doc(citiesRef, "DC"), {
        name: "Washington, D.C.", state: null, country: "USA",
        capital: true, population: 680000,
        regions: ["east_coast"] });
    await setDoc(doc(citiesRef, "TOK"), {
        name: "Tokyo", state: null, country: "Japan",
        capital: true, population: 9000000,
        regions: ["kanto", "honshu"] });
    await setDoc(doc(citiesRef, "BJ"), {
        name: "Beijing", state: null, country: "China",
        capital: true, population: 21500000,
        regions: ["jingjinji", "hebei"] });

    Web namespaced API

    var citiesRef = db.collection("cities");
    
    citiesRef.doc("SF").set({
        name: "San Francisco", state: "CA", country: "USA",
        capital: false, population: 860000,
        regions: ["west_coast", "norcal"] });
    citiesRef.doc("LA").set({
        name: "Los Angeles", state: "CA", country: "USA",
        capital: false, population: 3900000,
        regions: ["west_coast", "socal"] });
    citiesRef.doc("DC").set({
        name: "Washington, D.C.", state: null, country: "USA",
        capital: true, population: 680000,
        regions: ["east_coast"] });
    citiesRef.doc("TOK").set({
        name: "Tokyo", state: null, country: "Japan",
        capital: true, population: 9000000,
        regions: ["kanto", "honshu"] });
    citiesRef.doc("BJ").set({
        name: "Beijing", state: null, country: "China",
        capital: true, population: 21500000,
        regions: ["jingjinji", "hebei"] });
    तीव्र
    नोट: यह उत्पाद वॉचओएस और ऐप क्लिप लक्ष्य पर उपलब्ध नहीं है।
    let citiesRef = db.collection("cities")
    
    citiesRef.document("SF").setData([
      "name": "San Francisco",
      "state": "CA",
      "country": "USA",
      "capital": false,
      "population": 860000,
      "regions": ["west_coast", "norcal"]
    ])
    citiesRef.document("LA").setData([
      "name": "Los Angeles",
      "state": "CA",
      "country": "USA",
      "capital": false,
      "population": 3900000,
      "regions": ["west_coast", "socal"]
    ])
    citiesRef.document("DC").setData([
      "name": "Washington D.C.",
      "country": "USA",
      "capital": true,
      "population": 680000,
      "regions": ["east_coast"]
    ])
    citiesRef.document("TOK").setData([
      "name": "Tokyo",
      "country": "Japan",
      "capital": true,
      "population": 9000000,
      "regions": ["kanto", "honshu"]
    ])
    citiesRef.document("BJ").setData([
      "name": "Beijing",
      "country": "China",
      "capital": true,
      "population": 21500000,
      "regions": ["jingjinji", "hebei"]
    ])
    उद्देश्य सी
    नोट: यह उत्पाद वॉचओएस और ऐप क्लिप लक्ष्य पर उपलब्ध नहीं है।
    FIRCollectionReference *citiesRef = [self.db collectionWithPath:@"cities"];
    [[citiesRef documentWithPath:@"SF"] setData:@{
      @"name": @"San Francisco",
      @"state": @"CA",
      @"country": @"USA",
      @"capital": @(NO),
      @"population": @860000,
      @"regions": @[@"west_coast", @"norcal"]
    }];
    [[citiesRef documentWithPath:@"LA"] setData:@{
      @"name": @"Los Angeles",
      @"state": @"CA",
      @"country": @"USA",
      @"capital": @(NO),
      @"population": @3900000,
      @"regions": @[@"west_coast", @"socal"]
    }];
    [[citiesRef documentWithPath:@"DC"] setData:@{
      @"name": @"Washington D.C.",
      @"country": @"USA",
      @"capital": @(YES),
      @"population": @680000,
      @"regions": @[@"east_coast"]
    }];
    [[citiesRef documentWithPath:@"TOK"] setData:@{
      @"name": @"Tokyo",
      @"country": @"Japan",
      @"capital": @(YES),
      @"population": @9000000,
      @"regions": @[@"kanto", @"honshu"]
    }];
    [[citiesRef documentWithPath:@"BJ"] setData:@{
      @"name": @"Beijing",
      @"country": @"China",
      @"capital": @(YES),
      @"population": @21500000,
      @"regions": @[@"jingjinji", @"hebei"]
    }];

    Kotlin+KTX

    val cities = db.collection("cities")
    
    val data1 = hashMapOf(
        "name" to "San Francisco",
        "state" to "CA",
        "country" to "USA",
        "capital" to false,
        "population" to 860000,
        "regions" to listOf("west_coast", "norcal"),
    )
    cities.document("SF").set(data1)
    
    val data2 = hashMapOf(
        "name" to "Los Angeles",
        "state" to "CA",
        "country" to "USA",
        "capital" to false,
        "population" to 3900000,
        "regions" to listOf("west_coast", "socal"),
    )
    cities.document("LA").set(data2)
    
    val data3 = hashMapOf(
        "name" to "Washington D.C.",
        "state" to null,
        "country" to "USA",
        "capital" to true,
        "population" to 680000,
        "regions" to listOf("east_coast"),
    )
    cities.document("DC").set(data3)
    
    val data4 = hashMapOf(
        "name" to "Tokyo",
        "state" to null,
        "country" to "Japan",
        "capital" to true,
        "population" to 9000000,
        "regions" to listOf("kanto", "honshu"),
    )
    cities.document("TOK").set(data4)
    
    val data5 = hashMapOf(
        "name" to "Beijing",
        "state" to null,
        "country" to "China",
        "capital" to true,
        "population" to 21500000,
        "regions" to listOf("jingjinji", "hebei"),
    )
    cities.document("BJ").set(data5)

    Java

    CollectionReference cities = db.collection("cities");
    
    Map<String, Object> data1 = new HashMap<>();
    data1.put("name", "San Francisco");
    data1.put("state", "CA");
    data1.put("country", "USA");
    data1.put("capital", false);
    data1.put("population", 860000);
    data1.put("regions", Arrays.asList("west_coast", "norcal"));
    cities.document("SF").set(data1);
    
    Map<String, Object> data2 = new HashMap<>();
    data2.put("name", "Los Angeles");
    data2.put("state", "CA");
    data2.put("country", "USA");
    data2.put("capital", false);
    data2.put("population", 3900000);
    data2.put("regions", Arrays.asList("west_coast", "socal"));
    cities.document("LA").set(data2);
    
    Map<String, Object> data3 = new HashMap<>();
    data3.put("name", "Washington D.C.");
    data3.put("state", null);
    data3.put("country", "USA");
    data3.put("capital", true);
    data3.put("population", 680000);
    data3.put("regions", Arrays.asList("east_coast"));
    cities.document("DC").set(data3);
    
    Map<String, Object> data4 = new HashMap<>();
    data4.put("name", "Tokyo");
    data4.put("state", null);
    data4.put("country", "Japan");
    data4.put("capital", true);
    data4.put("population", 9000000);
    data4.put("regions", Arrays.asList("kanto", "honshu"));
    cities.document("TOK").set(data4);
    
    Map<String, Object> data5 = new HashMap<>();
    data5.put("name", "Beijing");
    data5.put("state", null);
    data5.put("country", "China");
    data5.put("capital", true);
    data5.put("population", 21500000);
    data5.put("regions", Arrays.asList("jingjinji", "hebei"));
    cities.document("BJ").set(data5);

    Dart

    final cities = db.collection("cities");
    final data1 = <String, dynamic>{
      "name": "San Francisco",
      "state": "CA",
      "country": "USA",
      "capital": false,
      "population": 860000,
      "regions": ["west_coast", "norcal"]
    };
    cities.doc("SF").set(data1);
    
    final data2 = <String, dynamic>{
      "name": "Los Angeles",
      "state": "CA",
      "country": "USA",
      "capital": false,
      "population": 3900000,
      "regions": ["west_coast", "socal"],
    };
    cities.doc("LA").set(data2);
    
    final data3 = <String, dynamic>{
      "name": "Washington D.C.",
      "state": null,
      "country": "USA",
      "capital": true,
      "population": 680000,
      "regions": ["east_coast"]
    };
    cities.doc("DC").set(data3);
    
    final data4 = <String, dynamic>{
      "name": "Tokyo",
      "state": null,
      "country": "Japan",
      "capital": true,
      "population": 9000000,
      "regions": ["kanto", "honshu"]
    };
    cities.doc("TOK").set(data4);
    
    final data5 = <String, dynamic>{
      "name": "Beijing",
      "state": null,
      "country": "China",
      "capital": true,
      "population": 21500000,
      "regions": ["jingjinji", "hebei"],
    };
    cities.doc("BJ").set(data5);
    जावा
    CollectionReference cities = db.collection("cities");
    List<ApiFuture<WriteResult>> futures = new ArrayList<>();
    futures.add(
        cities
            .document("SF")
            .set(
                new City(
                    "San Francisco",
                    "CA",
                    "USA",
                    false,
                    860000L,
                    Arrays.asList("west_coast", "norcal"))));
    futures.add(
        cities
            .document("LA")
            .set(
                new City(
                    "Los Angeles",
                    "CA",
                    "USA",
                    false,
                    3900000L,
                    Arrays.asList("west_coast", "socal"))));
    futures.add(
        cities
            .document("DC")
            .set(
                new City(
                    "Washington D.C.", null, "USA", true, 680000L, Arrays.asList("east_coast"))));
    futures.add(
        cities
            .document("TOK")
            .set(
                new City(
                    "Tokyo", null, "Japan", true, 9000000L, Arrays.asList("kanto", "honshu"))));
    futures.add(
        cities
            .document("BJ")
            .set(
                new City(
                    "Beijing",
                    null,
                    "China",
                    true,
                    21500000L,
                    Arrays.asList("jingjinji", "hebei"))));
    // (optional) block on operation
    ApiFutures.allAsList(futures).get();
    अजगर
    class City:
        def __init__(self, name, state, country, capital=False, population=0, regions=[]):
            self.name = name
            self.state = state
            self.country = country
            self.capital = capital
            self.population = population
            self.regions = regions
    
        @staticmethod
        def from_dict(source):
            # ...
    
        def to_dict(self):
            # ...
    
        def __repr__(self):
            return f"City(\
                    name={self.name}, \
                    country={self.country}, \
                    population={self.population}, \
                    capital={self.capital}, \
                    regions={self.regions}\
                )"
    
    
    cities_ref = db.collection("cities")
    cities_ref.document("BJ").set(
        City("Beijing", None, "China", True, 21500000, ["hebei"]).to_dict()
    )
    cities_ref.document("SF").set(
        City(
            "San Francisco", "CA", "USA", False, 860000, ["west_coast", "norcal"]
        ).to_dict()
    )
    cities_ref.document("LA").set(
        City(
            "Los Angeles", "CA", "USA", False, 3900000, ["west_coast", "socal"]
        ).to_dict()
    )
    cities_ref.document("DC").set(
        City("Washington D.C.", None, "USA", True, 680000, ["east_coast"]).to_dict()
    )
    cities_ref.document("TOK").set(
        City("Tokyo", None, "Japan", True, 9000000, ["kanto", "honshu"]).to_dict()
    )

    Python

    cities_ref = db.collection("cities")
    await cities_ref.document("BJ").set(
        City("Beijing", None, "China", True, 21500000, ["hebei"]).to_dict()
    )
    await cities_ref.document("SF").set(
        City(
            "San Francisco", "CA", "USA", False, 860000, ["west_coast", "norcal"]
        ).to_dict()
    )
    await cities_ref.document("LA").set(
        City(
            "Los Angeles", "CA", "USA", False, 3900000, ["west_coast", "socal"]
        ).to_dict()
    )
    await cities_ref.document("DC").set(
        City("Washington D.C.", None, "USA", True, 680000, ["east_coast"]).to_dict()
    )
    await cities_ref.document("TOK").set(
        City("Tokyo", None, "Japan", True, 9000000, ["kanto", "honshu"]).to_dict()
    )
    सी++
    CollectionReference cities = db->Collection("cities");
    
    cities.Document("SF").Set({
        {"name", FieldValue::String("San Francisco")},
        {"state", FieldValue::String("CA")},
        {"country", FieldValue::String("USA")},
        {"capital", FieldValue::Boolean(false)},
        {"population", FieldValue::Integer(860000)},
        {"regions", FieldValue::Array({FieldValue::String("west_coast"),
                                       FieldValue::String("norcal")})},
    });
    
    cities.Document("LA").Set({
        {"name", FieldValue::String("Los Angeles")},
        {"state", FieldValue::String("CA")},
        {"country", FieldValue::String("USA")},
        {"capital", FieldValue::Boolean(false)},
        {"population", FieldValue::Integer(3900000)},
        {"regions", FieldValue::Array({FieldValue::String("west_coast"),
                                       FieldValue::String("socal")})},
    });
    
    cities.Document("DC").Set({
        {"name", FieldValue::String("Washington D.C.")},
        {"state", FieldValue::Null()},
        {"country", FieldValue::String("USA")},
        {"capital", FieldValue::Boolean(true)},
        {"population", FieldValue::Integer(680000)},
        {"regions",
         FieldValue::Array({FieldValue::String("east_coast")})},
    });
    
    cities.Document("TOK").Set({
        {"name", FieldValue::String("Tokyo")},
        {"state", FieldValue::Null()},
        {"country", FieldValue::String("Japan")},
        {"capital", FieldValue::Boolean(true)},
        {"population", FieldValue::Integer(9000000)},
        {"regions", FieldValue::Array({FieldValue::String("kanto"),
                                       FieldValue::String("honshu")})},
    });
    
    cities.Document("BJ").Set({
        {"name", FieldValue::String("Beijing")},
        {"state", FieldValue::Null()},
        {"country", FieldValue::String("China")},
        {"capital", FieldValue::Boolean(true)},
        {"population", FieldValue::Integer(21500000)},
        {"regions", FieldValue::Array({FieldValue::String("jingjinji"),
                                       FieldValue::String("hebei")})},
    });
    नोड.जे.एस
    const citiesRef = db.collection('cities');
    
    await citiesRef.doc('SF').set({
      name: 'San Francisco', state: 'CA', country: 'USA',
      capital: false, population: 860000
    });
    await citiesRef.doc('LA').set({
      name: 'Los Angeles', state: 'CA', country: 'USA',
      capital: false, population: 3900000
    });
    await citiesRef.doc('DC').set({
      name: 'Washington, D.C.', state: null, country: 'USA',
      capital: true, population: 680000
    });
    await citiesRef.doc('TOK').set({
      name: 'Tokyo', state: null, country: 'Japan',
      capital: true, population: 9000000
    });
    await citiesRef.doc('BJ').set({
      name: 'Beijing', state: null, country: 'China',
      capital: true, population: 21500000
    });
    जाना
    
    import (
    	"context"
    
    	"cloud.google.com/go/firestore"
    )
    
    func prepareRetrieve(ctx context.Context, client *firestore.Client) error {
    	cities := []struct {
    		id string
    		c  City
    	}{
    		{id: "SF", c: City{Name: "San Francisco", State: "CA", Country: "USA", Capital: false, Population: 860000}},
    		{id: "LA", c: City{Name: "Los Angeles", State: "CA", Country: "USA", Capital: false, Population: 3900000}},
    		{id: "DC", c: City{Name: "Washington D.C.", Country: "USA", Capital: true, Population: 680000}},
    		{id: "TOK", c: City{Name: "Tokyo", Country: "Japan", Capital: true, Population: 9000000}},
    		{id: "BJ", c: City{Name: "Beijing", Country: "China", Capital: true, Population: 21500000}},
    	}
    	for _, c := range cities {
    		_, err := client.Collection("cities").Doc(c.id).Set(ctx, c.c)
    		if err != nil {
    			return err
    		}
    	}
    	return nil
    }
    
    पीएचपी

    पीएचपी

    क्लाउड फायरस्टोर क्लाइंट स्थापित करने और बनाने के बारे में अधिक जानकारी के लिए, क्लाउड फायरस्टोर क्लाइंट लाइब्रेरीज़ देखें।

    $citiesRef = $db->collection('samples/php/cities');
    $citiesRef->document('SF')->set([
        'name' => 'San Francisco',
        'state' => 'CA',
        'country' => 'USA',
        'capital' => false,
        'population' => 860000
    ]);
    $citiesRef->document('LA')->set([
        'name' => 'Los Angeles',
        'state' => 'CA',
        'country' => 'USA',
        'capital' => false,
        'population' => 3900000
    ]);
    $citiesRef->document('DC')->set([
        'name' => 'Washington D.C.',
        'state' => null,
        'country' => 'USA',
        'capital' => true,
        'population' => 680000
    ]);
    $citiesRef->document('TOK')->set([
        'name' => 'Tokyo',
        'state' => null,
        'country' => 'Japan',
        'capital' => true,
        'population' => 9000000
    ]);
    $citiesRef->document('BJ')->set([
        'name' => 'Beijing',
        'state' => null,
        'country' => 'China',
        'capital' => true,
        'population' => 21500000
    ]);
    printf('Added example cities data to the cities collection.' . PHP_EOL);
    एकता
    CollectionReference citiesRef = db.Collection("cities");
    citiesRef.Document("SF").SetAsync(new Dictionary<string, object>(){
            { "Name", "San Francisco" },
            { "State", "CA" },
            { "Country", "USA" },
            { "Capital", false },
            { "Population", 860000 }
        }).ContinueWithOnMainThread(task =>
            citiesRef.Document("LA").SetAsync(new Dictionary<string, object>(){
                { "Name", "Los Angeles" },
                { "State", "CA" },
                { "Country", "USA" },
                { "Capital", false },
                { "Population", 3900000 }
            })
    ).ContinueWithOnMainThread(task =>
        citiesRef.Document("DC").SetAsync(new Dictionary<string, object>(){
                { "Name", "Washington D.C." },
                { "State", null },
                { "Country", "USA" },
                { "Capital", true },
                { "Population", 680000 }
        })
    ).ContinueWithOnMainThread(task =>
        citiesRef.Document("TOK").SetAsync(new Dictionary<string, object>(){
                { "Name", "Tokyo" },
                { "State", null },
                { "Country", "Japan" },
                { "Capital", true },
                { "Population", 9000000 }
        })
    ).ContinueWithOnMainThread(task =>
        citiesRef.Document("BJ").SetAsync(new Dictionary<string, object>(){
                { "Name", "Beijing" },
                { "State", null },
                { "Country", "China" },
                { "Capital", true },
                { "Population", 21500000 }
        })
    );
    सी#
    CollectionReference citiesRef = db.Collection("cities");
    await citiesRef.Document("SF").SetAsync(new Dictionary<string, object>(){
        { "Name", "San Francisco" },
        { "State", "CA" },
        { "Country", "USA" },
        { "Capital", false },
        { "Population", 860000 }
    });
    await citiesRef.Document("LA").SetAsync(new Dictionary<string, object>(){
        { "Name", "Los Angeles" },
        { "State", "CA" },
        { "Country", "USA" },
        { "Capital", false },
        { "Population", 3900000 }
    });
    await citiesRef.Document("DC").SetAsync(new Dictionary<string, object>(){
        { "Name", "Washington D.C." },
        { "State", null },
        { "Country", "USA" },
        { "Capital", true },
        { "Population", 680000 }
    });
    await citiesRef.Document("TOK").SetAsync(new Dictionary<string, object>(){
        { "Name", "Tokyo" },
        { "State", null },
        { "Country", "Japan" },
        { "Capital", true },
        { "Population", 9000000 }
    });
    await citiesRef.Document("BJ").SetAsync(new Dictionary<string, object>(){
        { "Name", "Beijing" },
        { "State", null },
        { "Country", "China" },
        { "Capital", true },
        { "Population", 21500000 }
    });
    Console.WriteLine("Added example cities data to the cities collection.");
    माणिक
    cities_ref = firestore.col collection_path
    cities_ref.doc("SF").set(
      {
        name:       "San Francisco",
        state:      "CA",
        country:    "USA",
        capital:    false,
        population: 860_000
      }
    )
    cities_ref.doc("LA").set(
      {
        name:       "Los Angeles",
        state:      "CA",
        country:    "USA",
        capital:    false,
        population: 3_900_000
      }
    )
    cities_ref.doc("DC").set(
      {
        name:       "Washington D.C.",
        state:      nil,
        country:    "USA",
        capital:    true,
        population: 680_000
      }
    )
    cities_ref.doc("TOK").set(
      {
        name:       "Tokyo",
        state:      nil,
        country:    "Japan",
        capital:    true,
        population: 9_000_000
      }
    )
    cities_ref.doc("BJ").set(
      {
        name:       "Beijing",
        state:      nil,
        country:    "China",
        capital:    true,
        population: 21_500_000
      }
    )

    एक दस्तावेज़ प्राप्त करें

    निम्नलिखित उदाहरण दिखाता है कि get() का उपयोग करके एकल दस्तावेज़ की सामग्री को कैसे पुनः प्राप्त किया जाए:

    Web modular API

    import { doc, getDoc } from "firebase/firestore";
    
    const docRef = doc(db, "cities", "SF");
    const docSnap = await getDoc(docRef);
    
    if (docSnap.exists()) {
      console.log("Document data:", docSnap.data());
    } else {
      // docSnap.data() will be undefined in this case
      console.log("No such document!");
    }

    Web namespaced API

    var docRef = db.collection("cities").doc("SF");
    
    docRef.get().then((doc) => {
        if (doc.exists) {
            console.log("Document data:", doc.data());
        } else {
            // doc.data() will be undefined in this case
            console.log("No such document!");
        }
    }).catch((error) => {
        console.log("Error getting document:", error);
    });
    तीव्र
    नोट: यह उत्पाद वॉचओएस और ऐप क्लिप लक्ष्य पर उपलब्ध नहीं है।
    let docRef = db.collection("cities").document("SF")
    
    do {
      let document = try await docRef.getDocument()
      if document.exists {
        let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
        print("Document data: \(dataDescription)")
      } else {
        print("Document does not exist")
      }
    } catch {
      print("Error getting document: \(error)")
    }
    उद्देश्य सी
    नोट: यह उत्पाद वॉचओएस और ऐप क्लिप लक्ष्य पर उपलब्ध नहीं है।
    FIRDocumentReference *docRef =
        [[self.db collectionWithPath:@"cities"] documentWithPath:@"SF"];
    [docRef getDocumentWithCompletion:^(FIRDocumentSnapshot *snapshot, NSError *error) {
      if (snapshot.exists) {
        // Document data may be nil if the document exists but has no keys or values.
        NSLog(@"Document data: %@", snapshot.data);
      } else {
        NSLog(@"Document does not exist");
      }
    }];

    Kotlin+KTX

    val docRef = db.collection("cities").document("SF")
    docRef.get()
        .addOnSuccessListener { document ->
            if (document != null) {
                Log.d(TAG, "DocumentSnapshot data: ${document.data}")
            } else {
                Log.d(TAG, "No such document")
            }
        }
        .addOnFailureListener { exception ->
            Log.d(TAG, "get failed with ", exception)
        }

    Java

    DocumentReference docRef = db.collection("cities").document("SF");
    docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
            if (task.isSuccessful()) {
                DocumentSnapshot document = task.getResult();
                if (document.exists()) {
                    Log.d(TAG, "DocumentSnapshot data: " + document.getData());
                } else {
                    Log.d(TAG, "No such document");
                }
            } else {
                Log.d(TAG, "get failed with ", task.getException());
            }
        }
    });

    Dart

    final docRef = db.collection("cities").doc("SF");
    docRef.get().then(
      (DocumentSnapshot doc) {
        final data = doc.data() as Map<String, dynamic>;
        // ...
      },
      onError: (e) => print("Error getting document: $e"),
    );
    जावा
    DocumentReference docRef = db.collection("cities").document("SF");
    // asynchronously retrieve the document
    ApiFuture<DocumentSnapshot> future = docRef.get();
    // ...
    // future.get() blocks on response
    DocumentSnapshot document = future.get();
    if (document.exists()) {
      System.out.println("Document data: " + document.getData());
    } else {
      System.out.println("No such document!");
    }
    अजगर
    doc_ref = db.collection("cities").document("SF")
    
    doc = doc_ref.get()
    if doc.exists:
        print(f"Document data: {doc.to_dict()}")
    else:
        print("No such document!")

    Python

    doc_ref = db.collection("cities").document("SF")
    
    doc = await doc_ref.get()
    if doc.exists:
        print(f"Document data: {doc.to_dict()}")
    else:
        print("No such document!")
    सी++
    DocumentReference doc_ref = db->Collection("cities").Document("SF");
    doc_ref.Get().OnCompletion([](const Future<DocumentSnapshot>& future) {
      if (future.error() == Error::kErrorOk) {
        const DocumentSnapshot& document = *future.result();
        if (document.exists()) {
          std::cout << "DocumentSnapshot id: " << document.id() << std::endl;
        } else {
          std::cout << "no such document" << std::endl;
        }
      } else {
        std::cout << "Get failed with: " << future.error_message() << std::endl;
      }
    });
    नोड.जे.एस
    const cityRef = db.collection('cities').doc('SF');
    const doc = await cityRef.get();
    if (!doc.exists) {
      console.log('No such document!');
    } else {
      console.log('Document data:', doc.data());
    }
    जाना
    
    import (
    	"context"
    	"fmt"
    
    	"cloud.google.com/go/firestore"
    )
    
    func docAsMap(ctx context.Context, client *firestore.Client) (map[string]interface{}, error) {
    	dsnap, err := client.Collection("cities").Doc("SF").Get(ctx)
    	if err != nil {
    		return nil, err
    	}
    	m := dsnap.Data()
    	fmt.Printf("Document data: %#v\n", m)
    	return m, nil
    }
    
    पीएचपी

    पीएचपी

    क्लाउड फायरस्टोर क्लाइंट स्थापित करने और बनाने के बारे में अधिक जानकारी के लिए, क्लाउड फायरस्टोर क्लाइंट लाइब्रेरीज़ देखें।

    $docRef = $db->collection('samples/php/cities')->document('SF');
    $snapshot = $docRef->snapshot();
    
    if ($snapshot->exists()) {
        printf('Document data:' . PHP_EOL);
        print_r($snapshot->data());
    } else {
        printf('Document %s does not exist!' . PHP_EOL, $snapshot->id());
    }
    एकता
    DocumentReference docRef = db.Collection("cities").Document("SF");
    docRef.GetSnapshotAsync().ContinueWithOnMainThread(task =>
    {
      DocumentSnapshot snapshot = task.Result;
      if (snapshot.Exists) {
        Debug.Log(String.Format("Document data for {0} document:", snapshot.Id));
        Dictionary<string, object> city = snapshot.ToDictionary();
        foreach (KeyValuePair<string, object> pair in city) {
          Debug.Log(String.Format("{0}: {1}", pair.Key, pair.Value));
        }
      } else {
        Debug.Log(String.Format("Document {0} does not exist!", snapshot.Id));
      }
    });
    सी#
    DocumentReference docRef = db.Collection("cities").Document("SF");
    DocumentSnapshot snapshot = await docRef.GetSnapshotAsync();
    if (snapshot.Exists)
    {
        Console.WriteLine("Document data for {0} document:", snapshot.Id);
        Dictionary<string, object> city = snapshot.ToDictionary();
        foreach (KeyValuePair<string, object> pair in city)
        {
            Console.WriteLine("{0}: {1}", pair.Key, pair.Value);
        }
    }
    else
    {
        Console.WriteLine("Document {0} does not exist!", snapshot.Id);
    }
    माणिक
    doc_ref  = firestore.doc "#{collection_path}/SF"
    snapshot = doc_ref.get
    if snapshot.exists?
      puts "#{snapshot.document_id} data: #{snapshot.data}."
    else
      puts "Document #{snapshot.document_id} does not exist!"
    end

    स्रोत विकल्प

    ऑफ़लाइन समर्थन वाले प्लेटफ़ॉर्म के लिए, आप यह नियंत्रित करने के लिए source विकल्प सेट कर सकते हैं कि कॉल get ऑफ़लाइन कैश का उपयोग कैसे करता है।

    डिफ़ॉल्ट रूप से, एक get कॉल आपके डेटाबेस से नवीनतम दस्तावेज़ स्नैपशॉट लाने का प्रयास करेगी। ऑफ़लाइन समर्थन वाले प्लेटफ़ॉर्म पर, यदि नेटवर्क अनुपलब्ध है या अनुरोध का समय समाप्त हो गया है, तो क्लाइंट लाइब्रेरी ऑफ़लाइन कैश का उपयोग करेगी।

    आप डिफ़ॉल्ट व्यवहार को बदलने के लिए get() कॉल में source विकल्प निर्दिष्ट कर सकते हैं। आप केवल डेटाबेस से प्राप्त कर सकते हैं और ऑफ़लाइन कैश को अनदेखा कर सकते हैं, या आप केवल ऑफ़लाइन कैश से प्राप्त कर सकते हैं। उदाहरण के लिए:

    Web modular API

    import { doc, getDocFromCache } from "firebase/firestore";
    
    const docRef = doc(db, "cities", "SF");
    
    // Get a document, forcing the SDK to fetch from the offline cache.
    try {
      const doc = await getDocFromCache(docRef);
    
      // Document was found in the cache. If no cached document exists,
      // an error will be returned to the 'catch' block below.
      console.log("Cached document data:", doc.data());
    } catch (e) {
      console.log("Error getting cached document:", e);
    }

    Web namespaced API

    var docRef = db.collection("cities").doc("SF");
    
    // Valid options for source are 'server', 'cache', or
    // 'default'. See https://firebase.google.com/docs/reference/js/v8/firebase.firestore.GetOptions
    // for more information.
    var getOptions = {
        source: 'cache'
    };
    
    // Get a document, forcing the SDK to fetch from the offline cache.
    docRef.get(getOptions).then((doc) => {
        // Document was found in the cache. If no cached document exists,
        // an error will be returned to the 'catch' block below.
        console.log("Cached document data:", doc.data());
    }).catch((error) => {
        console.log("Error getting cached document:", error);
    });
    तीव्र
    नोट: यह उत्पाद वॉचओएस और ऐप क्लिप लक्ष्य पर उपलब्ध नहीं है।
    let docRef = db.collection("cities").document("SF")
    
    do {
      // Force the SDK to fetch the document from the cache. Could also specify
      // FirestoreSource.server or FirestoreSource.default.
      let document = try await docRef.getDocument(source: .cache)
      if document.exists {
        let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
        print("Cached document data: \(dataDescription)")
      } else {
        print("Document does not exist in cache")
      }
    } catch {
      print("Error getting document: \(error)")
    }
    उद्देश्य सी
    नोट: यह उत्पाद वॉचओएस और ऐप क्लिप लक्ष्य पर उपलब्ध नहीं है।
    FIRDocumentReference *docRef =
    [[self.db collectionWithPath:@"cities"] documentWithPath:@"SF"];
    
    // Force the SDK to fetch the document from the cache. Could also specify
    // FIRFirestoreSourceServer or FIRFirestoreSourceDefault.
    [docRef getDocumentWithSource:FIRFirestoreSourceCache
                       completion:^(FIRDocumentSnapshot *snapshot, NSError *error) {
      if (snapshot != NULL) {
        // The document data was found in the cache.
        NSLog(@"Cached document data: %@", snapshot.data);
      } else {
        // The document data was not found in the cache.
        NSLog(@"Document does not exist in cache: %@", error);
      }
    }];

    Kotlin+KTX

    val docRef = db.collection("cities").document("SF")
    
    // Source can be CACHE, SERVER, or DEFAULT.
    val source = Source.CACHE
    
    // Get the document, forcing the SDK to use the offline cache
    docRef.get(source).addOnCompleteListener { task ->
        if (task.isSuccessful) {
            // Document found in the offline cache
            val document = task.result
            Log.d(TAG, "Cached document data: ${document?.data}")
        } else {
            Log.d(TAG, "Cached get failed: ", task.exception)
        }
    }

    Java

    DocumentReference docRef = db.collection("cities").document("SF");
    
    // Source can be CACHE, SERVER, or DEFAULT.
    Source source = Source.CACHE;
    
    // Get the document, forcing the SDK to use the offline cache
    docRef.get(source).addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
            if (task.isSuccessful()) {
                // Document found in the offline cache
                DocumentSnapshot document = task.getResult();
                Log.d(TAG, "Cached document data: " + document.getData());
            } else {
                Log.d(TAG, "Cached get failed: ", task.getException());
            }
        }
    });

    Dart

    final docRef = db.collection("cities").doc("SF");
    
    // Source can be CACHE, SERVER, or DEFAULT.
    const source = Source.cache;
    
    docRef.get(const GetOptions(source: source)).then(
          (res) => print("Successfully completed"),
          onError: (e) => print("Error completing: $e"),
        );
    जावा

    जावा SDK में समर्थित नहीं है.

    अजगर

    पायथन एसडीके में समर्थित नहीं है।

    सी++
    DocumentReference doc_ref = db->Collection("cities").Document("SF");
    Source source = Source::kCache;
    doc_ref.Get(source).OnCompletion([](const Future<DocumentSnapshot>& future) {
      if (future.error() == Error::kErrorOk) {
        const DocumentSnapshot& document = *future.result();
        if (document.exists()) {
          std::cout << "Cached document id: " << document.id() << std::endl;
        } else {
        }
      } else {
        std::cout << "Cached get failed: " << future.error_message() << std::endl;
      }
    });
    नोड.जे.एस

    Node.js SDK में समर्थित नहीं है.

    जाना

    गो SDK में समर्थित नहीं है.

    पीएचपी

    PHP SDK में समर्थित नहीं है.

    एकता

    यूनिटी एसडीके में समर्थित नहीं है।

    सी#

    C# SDK में समर्थित नहीं है.

    माणिक

    रूबी एसडीके में समर्थित नहीं है।

    कस्टम ऑब्जेक्ट

    पिछले उदाहरण ने दस्तावेज़ की सामग्री को मानचित्र के रूप में पुनः प्राप्त किया, लेकिन कुछ भाषाओं में कस्टम ऑब्जेक्ट प्रकार का उपयोग करना अक्सर अधिक सुविधाजनक होता है। डेटा जोड़ें में, आपने एक City वर्ग परिभाषित किया जिसका उपयोग आप प्रत्येक शहर को परिभाषित करने के लिए करते थे। आप अपने दस्तावेज़ को वापस City ऑब्जेक्ट में बदल सकते हैं:

    कस्टम ऑब्जेक्ट का उपयोग करने के लिए, आपको अपनी कक्षा के लिए FirestoreDataConverter फ़ंक्शन को परिभाषित करना होगा। उदाहरण के लिए:

    Web modular API

    class City {
        constructor (name, state, country ) {
            this.name = name;
            this.state = state;
            this.country = country;
        }
        toString() {
            return this.name + ', ' + this.state + ', ' + this.country;
        }
    }
    
    // Firestore data converter
    const cityConverter = {
        toFirestore: (city) => {
            return {
                name: city.name,
                state: city.state,
                country: city.country
                };
        },
        fromFirestore: (snapshot, options) => {
            const data = snapshot.data(options);
            return new City(data.name, data.state, data.country);
        }
    };

    कस्टम ऑब्जेक्ट का उपयोग करने के लिए, आपको अपनी कक्षा के लिए FirestoreDataConverter फ़ंक्शन को परिभाषित करना होगा। उदाहरण के लिए:

    Web namespaced API

    class City {
        constructor (name, state, country ) {
            this.name = name;
            this.state = state;
            this.country = country;
        }
        toString() {
            return this.name + ', ' + this.state + ', ' + this.country;
        }
    }
    
    // Firestore data converter
    var cityConverter = {
        toFirestore: function(city) {
            return {
                name: city.name,
                state: city.state,
                country: city.country
                };
        },
        fromFirestore: function(snapshot, options){
            const data = snapshot.data(options);
            return new City(data.name, data.state, data.country);
        }
    };

    अपने रीड ऑपरेशंस के साथ अपने डेटा कनवर्टर को कॉल करें। रूपांतरण के बाद, आप कस्टम ऑब्जेक्ट विधियों तक पहुंच सकते हैं:

    Web modular API

    import { doc, getDoc} from "firebase/firestore"; 
    
    const ref = doc(db, "cities", "LA").withConverter(cityConverter);
    const docSnap = await getDoc(ref);
    if (docSnap.exists()) {
      // Convert to City object
      const city = docSnap.data();
      // Use a City instance method
      console.log(city.toString());
    } else {
      console.log("No such document!");
    }

    अपने रीड ऑपरेशंस के साथ अपने डेटा कनवर्टर को कॉल करें। रूपांतरण के बाद, आप कस्टम ऑब्जेक्ट विधियों तक पहुंच सकते हैं:

    Web namespaced API

    db.collection("cities").doc("LA")
      .withConverter(cityConverter)
      .get().then((doc) => {
        if (doc.exists){
          // Convert to City object
          var city = doc.data();
          // Use a City instance method
          console.log(city.toString());
        } else {
          console.log("No such document!");
        }}).catch((error) => {
          console.log("Error getting document:", error);
        });
    तीव्र
    नोट: यह उत्पाद वॉचओएस और ऐप क्लिप लक्ष्य पर उपलब्ध नहीं है।

    स्विफ्ट में स्वचालित प्रकार क्रमांकन का समर्थन करने के लिए, आपका प्रकार कोडेबल प्रोटोकॉल के अनुरूप होना चाहिए।

    let docRef = db.collection("cities").document("BJ")
    
    do {
      let city = try await docRef.getDocument(as: City.self)
      print("City: \(city)")
    } catch {
      print("Error decoding city: \(error)")
    }
    उद्देश्य सी
    नोट: यह उत्पाद वॉचओएस और ऐप क्लिप लक्ष्य पर उपलब्ध नहीं है।

    ऑब्जेक्टिव-सी में आपको इसे मैन्युअल रूप से करना होगा।

    FIRDocumentReference *docRef =
    [[self.db collectionWithPath:@"cities"] documentWithPath:@"BJ"];
    [docRef getDocumentWithCompletion:^(FIRDocumentSnapshot *snapshot, NSError *error) {
      FSTCity *city = [[FSTCity alloc] initWithDictionary:snapshot.data];
      if (city != nil) {
        NSLog(@"City: %@", city);
      } else {
        NSLog(@"Document does not exist");
      }
    }];

    Kotlin+KTX

    val docRef = db.collection("cities").document("BJ")
    docRef.get().addOnSuccessListener { documentSnapshot ->
        val city = documentSnapshot.toObject<City>()
    }

    Java

    महत्वपूर्ण: प्रत्येक कस्टम क्लास में एक सार्वजनिक कंस्ट्रक्टर होना चाहिए जो कोई तर्क नहीं लेता है। इसके अलावा, वर्ग में प्रत्येक संपत्ति के लिए एक सार्वजनिक गेटर शामिल होना चाहिए।

    DocumentReference docRef = db.collection("cities").document("BJ");
    docRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
        @Override
        public void onSuccess(DocumentSnapshot documentSnapshot) {
            City city = documentSnapshot.toObject(City.class);
        }
    });

    Dart

    कस्टम ऑब्जेक्ट का उपयोग करने के लिए, आपको अपनी कक्षा के लिए फायरस्टोर डेटा रूपांतरण फ़ंक्शन को परिभाषित करना होगा। उदाहरण के लिए:

    class City {
      final String? name;
      final String? state;
      final String? country;
      final bool? capital;
      final int? population;
      final List<String>? regions;
    
      City({
        this.name,
        this.state,
        this.country,
        this.capital,
        this.population,
        this.regions,
      });
    
      factory City.fromFirestore(
        DocumentSnapshot<Map<String, dynamic>> snapshot,
        SnapshotOptions? options,
      ) {
        final data = snapshot.data();
        return City(
          name: data?['name'],
          state: data?['state'],
          country: data?['country'],
          capital: data?['capital'],
          population: data?['population'],
          regions:
              data?['regions'] is Iterable ? List.from(data?['regions']) : null,
        );
      }
    
      Map<String, dynamic> toFirestore() {
        return {
          if (name != null) "name": name,
          if (state != null) "state": state,
          if (country != null) "country": country,
          if (capital != null) "capital": capital,
          if (population != null) "population": population,
          if (regions != null) "regions": regions,
        };
      }
    }

    फिर, अपने डेटा रूपांतरण कार्यों के साथ एक दस्तावेज़ संदर्भ बनाएं। इस संदर्भ का उपयोग करके आपके द्वारा किया गया कोई भी पठन ऑपरेशन आपके कस्टम वर्ग के उदाहरण लौटाएगा:

    final ref = db.collection("cities").doc("LA").withConverter(
          fromFirestore: City.fromFirestore,
          toFirestore: (City city, _) => city.toFirestore(),
        );
    final docSnap = await ref.get();
    final city = docSnap.data(); // Convert to City object
    if (city != null) {
      print(city);
    } else {
      print("No such document.");
    }
    जावा

    प्रत्येक कस्टम क्लास में एक सार्वजनिक कंस्ट्रक्टर होना चाहिए जो कोई तर्क नहीं लेता है। इसके अलावा, वर्ग में प्रत्येक संपत्ति के लिए एक सार्वजनिक गेटर शामिल होना चाहिए।

    DocumentReference docRef = db.collection("cities").document("BJ");
    // asynchronously retrieve the document
    ApiFuture<DocumentSnapshot> future = docRef.get();
    // block on response
    DocumentSnapshot document = future.get();
    City city = null;
    if (document.exists()) {
      // convert document to POJO
      city = document.toObject(City.class);
      System.out.println(city);
    } else {
      System.out.println("No such document!");
    }
    अजगर
    doc_ref = db.collection("cities").document("BJ")
    
    doc = doc_ref.get()
    city = City.from_dict(doc.to_dict())
    print(city)

    Python

    doc_ref = db.collection("cities").document("BJ")
    
    doc = await doc_ref.get()
    city = City.from_dict(doc.to_dict())
    print(city)
    सी++
    // This is not yet supported.
    
    नोड.जे.एस

    Node.js जावास्क्रिप्ट ऑब्जेक्ट का उपयोग करता है।

    जाना
    
    import (
    	"context"
    	"fmt"
    
    	"cloud.google.com/go/firestore"
    )
    
    func docAsEntity(ctx context.Context, client *firestore.Client) (*City, error) {
    	dsnap, err := client.Collection("cities").Doc("BJ").Get(ctx)
    	if err != nil {
    		return nil, err
    	}
    	var c City
    	dsnap.DataTo(&c)
    	fmt.Printf("Document data: %#v\n", c)
    	return &c, nil
    }
    
    पीएचपी

    पीएचपी

    क्लाउड फायरस्टोर क्लाइंट स्थापित करने और बनाने के बारे में अधिक जानकारी के लिए, क्लाउड फायरस्टोर क्लाइंट लाइब्रेरीज़ देखें।

    $docRef = $db->collection('samples/php/cities')->document('SF');
    $snapshot = $docRef->snapshot();
    $city = City::fromArray($snapshot->data());
    
    if ($snapshot->exists()) {
        printf('Document data:' . PHP_EOL);
        print((string) $city);
    } else {
        printf('Document %s does not exist!' . PHP_EOL, $snapshot->id());
    }
    एकता
    DocumentReference docRef = db.Collection("cities").Document("BJ");
    
    docRef.GetSnapshotAsync().ContinueWith((task) =>
    {
      var snapshot = task.Result;
      if (snapshot.Exists)
      {
        Debug.Log(String.Format("Document data for {0} document:", snapshot.Id));
        City city = snapshot.ConvertTo<City>();
        Debug.Log(String.Format("Name: {0}", city.Name));
        Debug.Log(String.Format("State: {0}", city.State));
        Debug.Log(String.Format("Country: {0}", city.Country));
        Debug.Log(String.Format("Capital: {0}", city.Capital));
        Debug.Log(String.Format("Population: {0}", city.Population));
      }
      else
      {
        Debug.Log(String.Format("Document {0} does not exist!", snapshot.Id));
      }
    });
    सी#
    DocumentReference docRef = db.Collection("cities").Document("BJ");
    DocumentSnapshot snapshot = await docRef.GetSnapshotAsync();
    if (snapshot.Exists)
    {
        Console.WriteLine("Document data for {0} document:", snapshot.Id);
        City city = snapshot.ConvertTo<City>();
        Console.WriteLine("Name: {0}", city.Name);
        Console.WriteLine("State: {0}", city.State);
        Console.WriteLine("Country: {0}", city.Country);
        Console.WriteLine("Capital: {0}", city.Capital);
        Console.WriteLine("Population: {0}", city.Population);
    }
    else
    {
        Console.WriteLine("Document {0} does not exist!", snapshot.Id);
    }
    माणिक

    रूबी के लिए लागू नहीं है.

    एक संग्रह से अनेक दस्तावेज़ प्राप्त करें

    आप एक संग्रह में दस्तावेज़ों की क्वेरी करके एक अनुरोध के साथ कई दस्तावेज़ भी पुनः प्राप्त कर सकते हैं। उदाहरण के लिए, आप एक निश्चित शर्त को पूरा करने वाले सभी दस्तावेज़ों के लिए क्वेरी करने के लिए where() उपयोग कर सकते हैं, फिर परिणाम प्राप्त करने के लिए get() उपयोग कर सकते हैं:

    Web modular API

    import { collection, query, where, getDocs } from "firebase/firestore";
    
    const q = query(collection(db, "cities"), where("capital", "==", true));
    
    const querySnapshot = await getDocs(q);
    querySnapshot.forEach((doc) => {
      // doc.data() is never undefined for query doc snapshots
      console.log(doc.id, " => ", doc.data());
    });

    Web namespaced API

    db.collection("cities").where("capital", "==", true)
        .get()
        .then((querySnapshot) => {
            querySnapshot.forEach((doc) => {
                // doc.data() is never undefined for query doc snapshots
                console.log(doc.id, " => ", doc.data());
            });
        })
        .catch((error) => {
            console.log("Error getting documents: ", error);
        });
    तीव्र
    नोट: यह उत्पाद वॉचओएस और ऐप क्लिप लक्ष्य पर उपलब्ध नहीं है।
    do {
      let querySnapshot = try await db.collection("cities").whereField("capital", isEqualTo: true)
        .getDocuments()
      for document in querySnapshot.documents {
        print("\(document.documentID) => \(document.data())")
      }
    } catch {
      print("Error getting documents: \(error)")
    }
    उद्देश्य सी
    नोट: यह उत्पाद वॉचओएस और ऐप क्लिप लक्ष्य पर उपलब्ध नहीं है।
    [[[self.db collectionWithPath:@"cities"] queryWhereField:@"capital" isEqualTo:@(YES)]
        getDocumentsWithCompletion:^(FIRQuerySnapshot *snapshot, NSError *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("cities")
        .whereEqualTo("capital", true)
        .get()
        .addOnSuccessListener { documents ->
            for (document in documents) {
                Log.d(TAG, "${document.id} => ${document.data}")
            }
        }
        .addOnFailureListener { exception ->
            Log.w(TAG, "Error getting documents: ", exception)
        }

    Java

    db.collection("cities")
            .whereEqualTo("capital", true)
            .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.d(TAG, "Error getting documents: ", task.getException());
                    }
                }
            });

    Dart

    db.collection("cities").where("capital", isEqualTo: true).get().then(
      (querySnapshot) {
        print("Successfully completed");
        for (var docSnapshot in querySnapshot.docs) {
          print('${docSnapshot.id} => ${docSnapshot.data()}');
        }
      },
      onError: (e) => print("Error completing: $e"),
    );
    जावा
    // asynchronously retrieve multiple documents
    ApiFuture<QuerySnapshot> future = db.collection("cities").whereEqualTo("capital", true).get();
    // future.get() blocks on response
    List<QueryDocumentSnapshot> documents = future.get().getDocuments();
    for (DocumentSnapshot document : documents) {
      System.out.println(document.getId() + " => " + document.toObject(City.class));
    }
    अजगर
    # Note: Use of CollectionRef stream() is prefered to get()
    docs = (
        db.collection("cities")
        .where(filter=FieldFilter("capital", "==", True))
        .stream()
    )
    
    for doc in docs:
        print(f"{doc.id} => {doc.to_dict()}")

    Python

    # Note: Use of CollectionRef stream() is prefered to get()
    docs = (
        db.collection("cities")
        .where(filter=FieldFilter("capital", "==", True))
        .stream()
    )
    
    async for doc in docs:
        print(f"{doc.id} => {doc.to_dict()}")
    सी++
    db->Collection("cities")
        .WhereEqualTo("capital", FieldValue::Boolean(true))
        .Get()
        .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;
          }
        });
    नोड.जे.एस
    const citiesRef = db.collection('cities');
    const snapshot = await citiesRef.where('capital', '==', true).get();
    if (snapshot.empty) {
      console.log('No matching documents.');
      return;
    }  
    
    snapshot.forEach(doc => {
      console.log(doc.id, '=>', doc.data());
    });
    जाना
    
    import (
    	"context"
    	"fmt"
    
    	"cloud.google.com/go/firestore"
    	"google.golang.org/api/iterator"
    )
    
    func multipleDocs(ctx context.Context, client *firestore.Client) error {
    	fmt.Println("All capital cities:")
    	iter := client.Collection("cities").Where("capital", "==", true).Documents(ctx)
    	for {
    		doc, err := iter.Next()
    		if err == iterator.Done {
    			break
    		}
    		if err != nil {
    			return err
    		}
    		fmt.Println(doc.Data())
    	}
    	return nil
    }
    
    पीएचपी

    पीएचपी

    क्लाउड फायरस्टोर क्लाइंट स्थापित करने और बनाने के बारे में अधिक जानकारी के लिए, क्लाउड फायरस्टोर क्लाइंट लाइब्रेरीज़ देखें।

    $citiesRef = $db->collection('samples/php/cities');
    $query = $citiesRef->where('capital', '=', true);
    $documents = $query->documents();
    foreach ($documents as $document) {
        if ($document->exists()) {
            printf('Document data for document %s:' . PHP_EOL, $document->id());
            print_r($document->data());
            printf(PHP_EOL);
        } else {
            printf('Document %s does not exist!' . PHP_EOL, $document->id());
        }
    }
    एकता
    Query capitalQuery = db.Collection("cities").WhereEqualTo("Capital", true);
    capitalQuery.GetSnapshotAsync().ContinueWithOnMainThread(task => {
      QuerySnapshot capitalQuerySnapshot = task.Result;
      foreach (DocumentSnapshot documentSnapshot in capitalQuerySnapshot.Documents) {
        Debug.Log(String.Format("Document data for {0} document:", documentSnapshot.Id));
        Dictionary<string, object> city = documentSnapshot.ToDictionary();
        foreach (KeyValuePair<string, object> pair in city) {
          Debug.Log(String.Format("{0}: {1}", pair.Key, pair.Value));
        }
    
        // Newline to separate entries
        Debug.Log("");
      };
    });
    सी#
    Query capitalQuery = db.Collection("cities").WhereEqualTo("Capital", true);
    QuerySnapshot capitalQuerySnapshot = await capitalQuery.GetSnapshotAsync();
    foreach (DocumentSnapshot documentSnapshot in capitalQuerySnapshot.Documents)
    {
        Console.WriteLine("Document data for {0} document:", documentSnapshot.Id);
        Dictionary<string, object> city = documentSnapshot.ToDictionary();
        foreach (KeyValuePair<string, object> pair in city)
        {
            Console.WriteLine("{0}: {1}", pair.Key, pair.Value);
        }
        Console.WriteLine("");
    }
    माणिक
    cities_ref = firestore.col collection_path
    
    query = cities_ref.where "capital", "=", true
    
    query.get do |city|
      puts "#{city.document_id} data: #{city.data}."
    end

    डिफ़ॉल्ट रूप से, क्लाउड फायरस्टोर उन सभी दस्तावेज़ों को पुनर्प्राप्त करता है जो दस्तावेज़ आईडी द्वारा आरोही क्रम में क्वेरी को संतुष्ट करते हैं, लेकिन आप लौटाए गए डेटा को ऑर्डर और सीमित कर सकते हैं।

    सभी दस्तावेज़ एक संग्रह में प्राप्त करें

    इसके अलावा, आप where() फ़िल्टर को पूरी तरह से हटाकर किसी संग्रह के सभी दस्तावेज़ पुनः प्राप्त कर सकते हैं:

    Web modular API

    import { collection, getDocs } from "firebase/firestore";
    
    const querySnapshot = await getDocs(collection(db, "cities"));
    querySnapshot.forEach((doc) => {
      // doc.data() is never undefined for query doc snapshots
      console.log(doc.id, " => ", doc.data());
    });

    Web namespaced API

    db.collection("cities").get().then((querySnapshot) => {
        querySnapshot.forEach((doc) => {
            // doc.data() is never undefined for query doc snapshots
            console.log(doc.id, " => ", doc.data());
        });
    });
    तीव्र
    नोट: यह उत्पाद वॉचओएस और ऐप क्लिप लक्ष्य पर उपलब्ध नहीं है।
    do {
      let querySnapshot = try await db.collection("cities").getDocuments()
      for document in querySnapshot.documents {
        print("\(document.documentID) => \(document.data())")
      }
    } catch {
      print("Error getting documents: \(error)")
    }
    उद्देश्य सी
    नोट: यह उत्पाद वॉचओएस और ऐप क्लिप लक्ष्य पर उपलब्ध नहीं है।
    [[self.db collectionWithPath:@"cities"]
        getDocumentsWithCompletion:^(FIRQuerySnapshot *snapshot, NSError *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("cities")
        .get()
        .addOnSuccessListener { result ->
            for (document in result) {
                Log.d(TAG, "${document.id} => ${document.data}")
            }
        }
        .addOnFailureListener { exception ->
            Log.d(TAG, "Error getting documents: ", exception)
        }

    Java

    db.collection("cities")
            .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.d(TAG, "Error getting documents: ", task.getException());
                    }
                }
            });

    Dart

    db.collection("cities").get().then(
      (querySnapshot) {
        print("Successfully completed");
        for (var docSnapshot in querySnapshot.docs) {
          print('${docSnapshot.id} => ${docSnapshot.data()}');
        }
      },
      onError: (e) => print("Error completing: $e"),
    );
    जावा
    // asynchronously retrieve all documents
    ApiFuture<QuerySnapshot> future = db.collection("cities").get();
    // future.get() blocks on response
    List<QueryDocumentSnapshot> documents = future.get().getDocuments();
    for (QueryDocumentSnapshot document : documents) {
      System.out.println(document.getId() + " => " + document.toObject(City.class));
    }
    अजगर
    docs = db.collection("cities").stream()
    
    for doc in docs:
        print(f"{doc.id} => {doc.to_dict()}")

    Python

    docs = db.collection("cities").stream()
    
    async for doc in docs:
        print(f"{doc.id} => {doc.to_dict()}")
    सी++
    db->Collection("cities").Get().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;
          }
        });
    नोड.जे.एस
    const citiesRef = db.collection('cities');
    const snapshot = await citiesRef.get();
    snapshot.forEach(doc => {
      console.log(doc.id, '=>', doc.data());
    });
    जाना
    
    import (
    	"context"
    	"fmt"
    
    	"cloud.google.com/go/firestore"
    	"google.golang.org/api/iterator"
    )
    
    func allDocs(ctx context.Context, client *firestore.Client) error {
    	fmt.Println("All cities:")
    	iter := client.Collection("cities").Documents(ctx)
    	for {
    		doc, err := iter.Next()
    		if err == iterator.Done {
    			break
    		}
    		if err != nil {
    			return err
    		}
    		fmt.Println(doc.Data())
    	}
    	return nil
    }
    
    पीएचपी

    पीएचपी

    क्लाउड फायरस्टोर क्लाइंट स्थापित करने और बनाने के बारे में अधिक जानकारी के लिए, क्लाउड फायरस्टोर क्लाइंट लाइब्रेरीज़ देखें।

    $citiesRef = $db->collection('samples/php/cities');
    $documents = $citiesRef->documents();
    foreach ($documents as $document) {
        if ($document->exists()) {
            printf('Document data for document %s:' . PHP_EOL, $document->id());
            print_r($document->data());
            printf(PHP_EOL);
        } else {
            printf('Document %s does not exist!' . PHP_EOL, $document->id());
        }
    }
    एकता
    Query allCitiesQuery = db.Collection("cities");
    allCitiesQuery.GetSnapshotAsync().ContinueWithOnMainThread(task =>
    {
      QuerySnapshot allCitiesQuerySnapshot = task.Result;
      foreach (DocumentSnapshot documentSnapshot in allCitiesQuerySnapshot.Documents)
      {
        Debug.Log(String.Format("Document data for {0} document:", documentSnapshot.Id));
        Dictionary<string, object> city = documentSnapshot.ToDictionary();
        foreach (KeyValuePair<string, object> pair in city)
        {
          Debug.Log(String.Format("{0}: {1}", pair.Key, pair.Value));
        }
    
        // Newline to separate entries
        Debug.Log("");
      }
    });
    सी#
    Query allCitiesQuery = db.Collection("cities");
    QuerySnapshot allCitiesQuerySnapshot = await allCitiesQuery.GetSnapshotAsync();
    foreach (DocumentSnapshot documentSnapshot in allCitiesQuerySnapshot.Documents)
    {
        Console.WriteLine("Document data for {0} document:", documentSnapshot.Id);
        Dictionary<string, object> city = documentSnapshot.ToDictionary();
        foreach (KeyValuePair<string, object> pair in city)
        {
            Console.WriteLine("{0}: {1}", pair.Key, pair.Value);
        }
        Console.WriteLine("");
    }
    माणिक
    cities_ref = firestore.col collection_path
    cities_ref.get do |city|
      puts "#{city.document_id} data: #{city.data}."
    end

    सभी दस्तावेज़ों को एक उपसंग्रह में प्राप्त करें

    किसी उपसंग्रह से सभी दस्तावेज़ पुनर्प्राप्त करने के लिए, उस उपसंग्रह के संपूर्ण पथ के साथ एक संदर्भ बनाएं:

    Web modular API

    const { collection, getDocs } = require("firebase/firestore");
    // Query a reference to a subcollection
    const querySnapshot = await getDocs(collection(db, "cities", "SF", "landmarks"));
    querySnapshot.forEach((doc) => {
      // doc.data() is never undefined for query doc snapshots
      console.log(doc.id, " => ", doc.data());
    });

    Web namespaced API

    // Snippet not available
    तीव्र
    do {
      let querySnapshot = try await db.collection("cities/SF/landmarks").getDocuments()
      for document in querySnapshot.documents {
        print("\(document.documentID) => \(document.data())")
      }
    } catch {
      print("Error getting documents: \(error)")
    }
    उद्देश्य सी
    [[self.db collectionWithPath:@"cities/SF/landmarks"]
        getDocumentsWithCompletion:^(FIRQuerySnapshot *snapshot, NSError *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("cities")
        .document("SF")
        .collection("landmarks")
        .get()
        .addOnSuccessListener { result ->
            for (document in result) {
                Log.d(TAG, "${document.id} => ${document.data}")
            }
        }
        .addOnFailureListener { exception ->
            Log.d(TAG, "Error getting documents: ", exception)
        }

    Java

    db.collection("cities")
            .document("SF")
            .collection("landmarks")
            .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.d(TAG, "Error getting documents: ", task.getException());
                    }
                }
            });

    Dart

    db.collection("cities").doc("SF").collection("landmarks").get().then(
      (querySnapshot) {
        print("Successfully completed");
        for (var docSnapshot in querySnapshot.docs) {
          print('${docSnapshot.id} => ${docSnapshot.data()}');
        }
      },
      onError: (e) => print("Error completing: $e"),
    );
    जावा
    // Snippet not available
    अजगर
    // Snippet not available

    Python

    // Snippet not available
    सी++
    // Snippet not available
    नोड.जे.एस
    // Snippet not available
    जाना
    // Snippet not available
    पीएचपी
    // Snippet not available
    एकता
    // Snippet not available
    सी#
    // Snippet not available
    माणिक
    // Snippet not available

    एक संग्रह समूह से एकाधिक दस्तावेज़ प्राप्त करें

    एक संग्रह समूह में एक ही आईडी वाले सभी संग्रह शामिल होते हैं। उदाहरण के लिए, यदि आपके cities संग्रह में प्रत्येक दस्तावेज़ में एक उपसंग्रह है जिसे landmarks कहा जाता है, तो सभी landmarks उपसंग्रह एक ही संग्रह समूह से संबंधित हैं। डिफ़ॉल्ट रूप से, क्वेरीज़ आपके डेटाबेस में एकल संग्रह से परिणाम प्राप्त करती हैं। एकल संग्रह के बजाय संग्रह समूह से परिणाम प्राप्त करने के लिए संग्रह समूह क्वेरी का उपयोग करें

    किसी दस्तावेज़ के उपसंग्रहों की सूची बनाएं

    क्लाउड फायरस्टोर सर्वर क्लाइंट लाइब्रेरीज़ की listCollections() विधि दस्तावेज़ संदर्भ के सभी उपसंग्रहों को सूचीबद्ध करती है।

    मोबाइल/वेब क्लाइंट लाइब्रेरीज़ के साथ संग्रहों की सूची पुनर्प्राप्त करना संभव नहीं है। आपको केवल विश्वसनीय सर्वर वातावरण में प्रशासनिक कार्यों के हिस्से के रूप में संग्रह नाम देखना चाहिए। यदि आपको लगता है कि आपको मोबाइल/वेब क्लाइंट लाइब्रेरी में इस क्षमता की आवश्यकता है, तो अपने डेटा को पुनर्गठित करने पर विचार करें ताकि उपसंग्रह नाम पूर्वानुमानित हो सकें।

    वेब

    वेब क्लाइंट लाइब्रेरी में उपलब्ध नहीं है.

    तीव्र

    स्विफ्ट क्लाइंट लाइब्रेरी में उपलब्ध नहीं है।

    उद्देश्य सी

    ऑब्जेक्टिव-सी क्लाइंट लाइब्रेरी में उपलब्ध नहीं है।

    Kotlin+KTX

    एंड्रॉइड क्लाइंट लाइब्रेरी में उपलब्ध नहीं है।

    Java

    एंड्रॉइड क्लाइंट लाइब्रेरी में उपलब्ध नहीं है।

    Dart

    फ़्लटर क्लाइंट लाइब्रेरी में उपलब्ध नहीं है।

    जावा
    Iterable<CollectionReference> collections =
        db.collection("cities").document("SF").listCollections();
    
    for (CollectionReference collRef : collections) {
      System.out.println("Found subcollection with id: " + collRef.getId());
    }
    अजगर
    collections = db.collection("cities").document("SF").collections()
    for collection in collections:
        for doc in collection.stream():
            print(f"{doc.id} => {doc.to_dict()}")

    Python

    collections = db.collection("cities").document("SF").collections()
    async for collection in collections:
        async for doc in collection.stream():
            print(f"{doc.id} => {doc.to_dict()}")
    सी++

    C++ क्लाइंट लाइब्रेरी में उपलब्ध नहीं है।

    नोड.जे.एस
    const sfRef = db.collection('cities').doc('SF');
    const collections = await sfRef.listCollections();
    collections.forEach(collection => {
      console.log('Found subcollection with id:', collection.id);
    });
    जाना
    
    import (
    	"context"
    	"fmt"
    
    	"cloud.google.com/go/firestore"
    	"google.golang.org/api/iterator"
    )
    
    func getCollections(ctx context.Context, client *firestore.Client) error {
    	iter := client.Collection("cities").Doc("SF").Collections(ctx)
    	for {
    		collRef, err := iter.Next()
    		if err == iterator.Done {
    			break
    		}
    		if err != nil {
    			return err
    		}
    		fmt.Printf("Found collection with id: %s\n", collRef.ID)
    	}
    	return nil
    }
    
    पीएचपी

    पीएचपी

    क्लाउड फायरस्टोर क्लाइंट स्थापित करने और बनाने के बारे में अधिक जानकारी के लिए, क्लाउड फायरस्टोर क्लाइंट लाइब्रेरीज़ देखें।

    $cityRef = $db->collection('samples/php/cities')->document('SF');
    $collections = $cityRef->collections();
    foreach ($collections as $collection) {
        printf('Found subcollection with id: %s' . PHP_EOL, $collection->id());
    }
    एकता
    // This is not yet supported in the Unity SDK.
    
    सी#
    DocumentReference cityRef = db.Collection("cities").Document("SF");
    IAsyncEnumerable<CollectionReference> subcollections = cityRef.ListCollectionsAsync();
    IAsyncEnumerator<CollectionReference> subcollectionsEnumerator = subcollections.GetAsyncEnumerator(default);
    while (await subcollectionsEnumerator.MoveNextAsync())
    {
        CollectionReference subcollectionRef = subcollectionsEnumerator.Current;
        Console.WriteLine("Found subcollection with ID: {0}", subcollectionRef.Id);
    }
    माणिक
    city_ref = firestore.doc "#{collection_path}/SF"
    city_ref.cols do |col|
      puts col.collection_id
    end

    विभिन्न प्रकार की क्वेरीज़ के बारे में और जानें.

    त्रुटि कोड पर अधिक जानकारी और डेटा प्राप्त करते समय विलंबता समस्याओं को हल करने के तरीके के लिए समस्या निवारण पृष्ठ देखें।