查詢子集合

示範如何查詢子集合。

深入探索

如需包含這個程式碼範例的詳細說明文件,請參閱下列文章:

程式碼範例

C#

如要向 Firestore 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

CollectionReference landmarks = db.Collection("cities").Document("SF").Collection("landmarks");
QuerySnapshot querySnapshot = await landmarks.GetSnapshotAsync();
foreach (DocumentSnapshot document in querySnapshot.Documents)
{
    Console.WriteLine($"{document.Reference.Path}: {document.GetValue<string>("Name")}");
}

Java

如要向 Firestore 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

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

Kotlin

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

Node.js

如要向 Firestore 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

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

後續步驟

如要搜尋及篩選其他 Google Cloud 產品的程式碼範例,請參閱Google Cloud 範例瀏覽工具