Supprimer une collection Firestore
Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Supprimer une collection Firestore et les documents qu'elle contient.
En savoir plus
Pour obtenir une documentation détaillée incluant cet exemple de code, consultez les articles suivants :
Exemple de code
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","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\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\nC#\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\nGo\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\nJava\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\nNode.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\nPHP\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\nPython\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\nRuby\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\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=firestore)."]]