刪除 Firestore 集合
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
刪除 Firestore 集合和其中的文件。
深入探索
如需包含這個程式碼範例的詳細說明文件,請參閱下列內容:
程式碼範例
Java
如要向 Firestore 進行驗證,請設定應用程式預設憑證。
詳情請參閱「為本機開發環境設定驗證」。
Node.js
如要向 Firestore 進行驗證,請設定應用程式預設憑證。
詳情請參閱「為本機開發環境設定驗證」。
PHP
如要向 Firestore 進行驗證,請設定應用程式預設憑證。
詳情請參閱「為本機開發環境設定驗證」。
Python
如要向 Firestore 進行驗證,請設定應用程式預設憑證。
詳情請參閱「為本機開發環境設定驗證」。
Ruby
如要向 Firestore 進行驗證,請設定應用程式預設憑證。
詳情請參閱「為本機開發環境設定驗證」。
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["難以理解","hardToUnderstand","thumb-down"],["資訊或程式碼範例有誤","incorrectInformationOrSampleCode","thumb-down"],["缺少我需要的資訊/範例","missingTheInformationSamplesINeed","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["其他","otherDown","thumb-down"]],[],[[["\u003cp\u003eThis page provides code samples for deleting a Firestore collection and its documents across multiple programming languages.\u003c/p\u003e\n"],["\u003cp\u003eThe code examples demonstrate how to delete documents in batches to avoid memory issues, iterating through documents and deleting them sequentially or with batch operations.\u003c/p\u003e\n"],["\u003cp\u003eEach code sample language uses Application Default Credentials for Firestore authentication, with a link for more details on setting this up locally.\u003c/p\u003e\n"],["\u003cp\u003eThe code examples provided showcase implementations in C#, Go, Java, Node.js, PHP, Python, and Ruby.\u003c/p\u003e\n"],["\u003cp\u003eThe page also directs users to the Google Cloud sample browser for additional code samples related to other Google Cloud products.\u003c/p\u003e\n"]]],[],null,["# Delete a Firestore collection and documents within.\n\nExplore further\n---------------\n\n\nFor detailed documentation that includes this code sample, see the following:\n\n- [Delete data from Cloud Firestore](https://firebase.google.com/docs/firestore/manage-data/delete-data)\n- [Delete documents and fields](/firestore/native/docs/manage-data/delete-data)\n\nCode sample\n-----------\n\n### C#\n\n\nTo authenticate to Firestore, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n private static async Task DeleteCollection(CollectionReference collectionReference, int batchSize)\n {\n QuerySnapshot snapshot = await collectionReference.Limit(batchSize).GetSnapshotAsync();\n IReadOnlyList\u003cDocumentSnapshot\u003e documents = snapshot.Documents;\n while (documents.Count \u003e 0)\n {\n foreach (DocumentSnapshot document in documents)\n {\n Console.WriteLine(\"Deleting document {0}\", document.Id);\n await document.Reference.DeleteAsync();\n }\n snapshot = await collectionReference.Limit(batchSize).GetSnapshotAsync();\n documents = snapshot.Documents;\n }\n Console.WriteLine(\"Finished deleting all documents from the collection.\");\n }\n\n### Go\n\n\nTo authenticate to Firestore, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n import (\n \t\"context\"\n \t\"fmt\"\n \t\"io\"\n\n \t\"cloud.google.com/go/firestore\"\n \t\"google.golang.org/api/iterator\"\n )\n\n func deleteCollection(w io.Writer, projectID, collectionName string,\n \tbatchSize int) error {\n\n \t// Instantiate a client\n \tctx := context.Background()\n \tclient, err := firestore.NewClient(ctx, projectID)\n \tif err != nil {\n \t\treturn err\n \t}\n\n \tcol := client.Collection(collectionName)\n \tbulkwriter := client.BulkWriter(ctx)\n\n \tfor {\n \t\t// Get a batch of documents\n \t\titer := col.https://cloud.google.com/go/docs/reference/cloud.google.com/go/firestore/latest/index.html#cloud_google_com_go_firestore_Query_Limit(batchSize).Documents(ctx)\n \t\tnumDeleted := 0\n\n \t\t// Iterate through the documents, adding\n \t\t// a delete operation for each one to the BulkWriter.\n \t\tfor {\n \t\t\tdoc, err := iter.Next()\n \t\t\tif err == iterator.Done {\n \t\t\t\tbreak\n \t\t\t}\n \t\t\tif err != nil {\n \t\t\t\treturn err\n \t\t\t}\n\n \t\t\tbulkwriter.Delete(doc.Ref)\n \t\t\tnumDeleted++\n \t\t}\n\n \t\t// If there are no documents to delete,\n \t\t// the process is over.\n \t\tif numDeleted == 0 {\n \t\t\tbulkwriter.https://cloud.google.com/go/docs/reference/cloud.google.com/go/firestore/latest/index.html#cloud_google_com_go_firestore_BulkWriter_End()\n \t\t\tbreak\n \t\t}\n\n \t\tbulkwriter.https://cloud.google.com/go/docs/reference/cloud.google.com/go/firestore/latest/index.html#cloud_google_com_go_firestore_BulkWriter_Flush()\n \t}\n \tfmt.Fprintf(w, \"Deleted collection \\\"%s\\\"\", collectionName)\n \treturn nil\n }\n\n### Java\n\n\nTo authenticate to Firestore, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n /**\n * Delete a collection in batches to avoid out-of-memory errors. Batch size may be tuned based on\n * document size (atmost 1MB) and application requirements.\n */\n void deleteCollection(CollectionReference collection, int batchSize) {\n try {\n // retrieve a small batch of documents to avoid out-of-memory errors\n ApiFuture\u003cQuerySnapshot\u003e future = collection.limit(batchSize).get();\n int deleted = 0;\n // future.get() blocks on document retrieval\n List\u003cQueryDocumentSnapshot\u003e documents = future.get().getDocuments();\n for (QueryDocumentSnapshot document : documents) {\n document.getReference().delete();\n ++deleted;\n }\n if (deleted \u003e= batchSize) {\n // retrieve and delete another batch\n deleteCollection(collection, batchSize);\n }\n } catch (Exception e) {\n System.err.println(\"Error deleting collection : \" + e.getMessage());\n }\n }\n\n### Node.js\n\n\nTo authenticate to Firestore, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n async function deleteCollection(db, collectionPath, batchSize) {\n const collectionRef = db.collection(collectionPath);\n const query = collectionRef.orderBy('__name__').limit(batchSize);\n\n return new Promise((resolve, reject) =\u003e {\n deleteQueryBatch(db, query, resolve).catch(reject);\n });\n }\n\n async function deleteQueryBatch(db, query, resolve) {\n const snapshot = await query.get();\n\n const batchSize = snapshot.size;\n if (batchSize === 0) {\n // When there are no documents left, we are done\n resolve();\n return;\n }\n\n // Delete documents in a batch\n const batch = db.batch();\n snapshot.docs.forEach((doc) =\u003e {\n batch.delete(doc.ref);\n });\n await batch.commit();\n\n // Recurse on the next process tick, to avoid\n // exploding the stack.\n process.nextTick(() =\u003e {\n deleteQueryBatch(db, query, resolve);\n });\n }\n\n### PHP\n\n\nTo authenticate to Firestore, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n function data_delete_collection(string $projectId, string $collectionName, int $batchSize)\n {\n // Create the Cloud Firestore client\n $db = new FirestoreClient([\n 'projectId' =\u003e $projectId,\n ]);\n $collectionReference = $db-\u003ecollection($collectionName);\n $documents = $collectionReference-\u003elimit($batchSize)-\u003edocuments();\n while (!$documents-\u003eisEmpty()) {\n foreach ($documents as $document) {\n printf('Deleting document %s' . PHP_EOL, $document-\u003eid());\n $document-\u003ereference()-\u003edelete();\n }\n $documents = $collectionReference-\u003elimit($batchSize)-\u003edocuments();\n }\n }\n\n### Python\n\n\nTo authenticate to Firestore, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n def delete_collection(coll_ref, batch_size):\n if batch_size == 0:\n return\n\n docs = coll_ref.list_documents(page_size=batch_size)\n deleted = 0\n\n for doc in docs:\n print(f\"Deleting doc {doc.id} =\u003e {doc.get().to_dict()}\")\n doc.delete()\n deleted = deleted + 1\n\n if deleted \u003e= batch_size:\n return delete_collection(coll_ref, batch_size)\n\n### Ruby\n\n\nTo authenticate to Firestore, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n cities_ref = firestore.col collection_path\n query = cities_ref\n\n query.get do |document_snapshot|\n puts \"Deleting document #{document_snapshot.document_id}.\"\n document_ref = document_snapshot.ref\n document_ref.delete\n end\n\nWhat's next\n-----------\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=firestore)."]]