Delete data from Cloud Firestore Stay organized with collections Save and categorize content based on your preferences.
The following examples demonstrate how to delete documents, fields, andcollections.
Delete documents
To delete a document, use the following language-specificdelete() methods:
Web
Use thedeleteDoc() method:
import{doc,deleteDoc}from"firebase/firestore";awaitdeleteDoc(doc(db,"cities","DC"));
Web
Use thedelete() method:
db.collection("cities").doc("DC").delete().then(()=>{console.log("Document successfully deleted!");}).catch((error)=>{console.error("Error removing document: ",error);});
Swift
Use thedelete() method:
do{tryawaitdb.collection("cities").document("DC").delete()print("Document successfully removed!")}catch{print("Error removing document:\(error)")}
Objective-C
Use thedeleteDocumentWithCompletion: method:
[[[self.dbcollectionWithPath:@"cities"]documentWithPath:@"DC"]deleteDocumentWithCompletion:^(NSError*_Nullableerror){if(error!=nil){NSLog(@"Error removing document: %@",error);}else{NSLog(@"Document successfully removed!");}}];
Kotlin
Use thedelete() method:
db.collection("cities").document("DC").delete().addOnSuccessListener{Log.d(TAG,"DocumentSnapshot successfully deleted!")}.addOnFailureListener{e->Log.w(TAG,"Error deleting document",e)}
Java
Use thedelete() method:
db.collection("cities").document("DC").delete().addOnSuccessListener(newOnSuccessListener<Void>(){@OverridepublicvoidonSuccess(VoidaVoid){Log.d(TAG,"DocumentSnapshot successfully deleted!");}}).addOnFailureListener(newOnFailureListener(){@OverridepublicvoidonFailure(@NonNullExceptione){Log.w(TAG,"Error deleting document",e);}});
Dart
Use thedelete() method:
db.collection("cities").doc("DC").delete().then((doc)=>print("Document deleted"),onError:(e)=>print("Error updating document$e"),);
Java
Use thedelete() method:
// asynchronously delete a documentApiFuture<WriteResult>writeResult=db.collection("cities").document("DC").delete();// ...System.out.println("Update time : "+writeResult.get().getUpdateTime());Python
Use thedelete() method:
db.collection("cities").document("DC").delete()Python
Use thedelete() method:
awaitdb.collection("cities").document("DC").delete()C++
Use theDelete() method:
db->Collection("cities").Document("DC").Delete().OnCompletion([](constFuture<void>&future){if(future.error()==Error::kErrorOk){std::cout <<"DocumentSnapshot successfully deleted!" <<std::endl;}else{std::cout <<"Error deleting document: " <<future.error_message() <<std::endl;}});
Node.js
Use thedelete() method:
constres=awaitdb.collection('cities').doc('DC').delete();Go
Use theDelete() method:
import("context""log""cloud.google.com/go/firestore")funcdeleteDoc(ctxcontext.Context,client*firestore.Client)error{_,err:=client.Collection("cities").Doc("DC").Delete(ctx)iferr!=nil{// Handle any errors in an appropriate way, such as returning them.log.Printf("An error has occurred: %s",err)}returnerr}PHP
Use thedelete() method:
$db->collection('samples/php/cities')->document('DC')->delete();Unity
Use theDeleteAsync() method:
DocumentReferencecityRef=db.Collection("cities").Document("DC");cityRef.DeleteAsync();
C#
Use theDeleteAsync() method:
DocumentReferencecityRef=db.Collection("cities").Document("DC");awaitcityRef.DeleteAsync();Ruby
Use thedelete() method:
city_ref=firestore.doc"#{collection_path}/DC"city_ref.deleteWhen you delete a document,Cloud Firestore does not automaticallydelete the documents within itssubcollections. You can still access the subcollection documents by reference.For example, you can access the document at path/mycoll/mydoc/mysubcoll/mysubdoc evenif you delete the ancestor document at/mycoll/mydoc.
Non-existent ancestor documentsappear in the console,but they do not appear in query results and snapshots.
If you want to delete a document and all the documents within itssubcollections, you must do so manually. For more information, seeDelete Collections.
Delete fields
To delete specific fields from a document, use the following language-specificFieldValue.delete() methodswhen you update a document:
Web
Use thedeleteField() method:
import{doc,updateDoc,deleteField}from"firebase/firestore";constcityRef=doc(db,'cities','BJ');// Remove the 'capital' field from the documentawaitupdateDoc(cityRef,{capital:deleteField()});
Web
Use theFieldValue.delete() method:
varcityRef=db.collection('cities').doc('BJ');// Remove the 'capital' field from the documentvarremoveCapital=cityRef.update({capital:firebase.firestore.FieldValue.delete()});
Swift
Use theFieldValue.delete() method:
do{tryawaitdb.collection("cities").document("BJ").updateData(["capital":FieldValue.delete(),])print("Document successfully updated")}catch{print("Error updating document:\(error)")}
Objective-C
Use thefieldValueForDelete: method:
[[[self.dbcollectionWithPath:@"cities"]documentWithPath:@"BJ"]updateData:@{@"capital":[FIRFieldValuefieldValueForDelete]}completion:^(NSError*_Nullableerror){if(error!=nil){NSLog(@"Error updating document: %@",error);}else{NSLog(@"Document successfully updated");}}];
Kotlin
Use theFieldValue.delete() method:
valdocRef=db.collection("cities").document("BJ")// Remove the 'capital' field from the documentvalupdates=hashMapOf<String,Any>("capital"toFieldValue.delete(),)docRef.update(updates).addOnCompleteListener{}
Java
Use theFieldValue.delete() method:
DocumentReferencedocRef=db.collection("cities").document("BJ");// Remove the 'capital' field from the documentMap<String,Object>updates=newHashMap<>();updates.put("capital",FieldValue.delete());docRef.update(updates).addOnCompleteListener(newOnCompleteListener<Void>(){// ...// ...
Dart
Use theFieldValue.delete() method:
finaldocRef=db.collection("cities").doc("BJ");// Remove the 'capital' field from the documentfinalupdates=<String,dynamic>{"capital":FieldValue.delete(),};docRef.update(updates);
Java
Use theFieldValue.delete() method:
DocumentReferencedocRef=db.collection("cities").document("BJ");Map<String,Object>updates=newHashMap<>();updates.put("capital",FieldValue.delete());// Update and delete the "capital" field in the documentApiFuture<WriteResult>writeResult=docRef.update(updates);System.out.println("Update time : "+writeResult.get());Python
Use thefirestore.DELETE_FIELD method:
city_ref=db.collection("cities").document("BJ")city_ref.update({"capital":firestore.DELETE_FIELD})Python
Use thefirestore.DELETE_FIELD method:
city_ref=db.collection("cities").document("BJ")awaitcity_ref.update({"capital":firestore.DELETE_FIELD})C++
Use theFieldValue::Delete() method:
DocumentReferencedoc_ref=db->Collection("cities").Document("BJ");doc_ref.Update({{"capital", FieldValue::Delete()}}).OnCompletion([](constFuture<void>&future){/*...*/});
Node.js
Use theFieldValue.delete() method:
// Create a document referenceconstcityRef=db.collection('cities').doc('BJ');// Remove the 'capital' field from the documentconstres=awaitcityRef.update({capital:FieldValue.delete()});Go
Use thefirestore.Delete method:
import("context""log""cloud.google.com/go/firestore")funcdeleteField(ctxcontext.Context,client*firestore.Client)error{_,err:=client.Collection("cities").Doc("BJ").Update(ctx,[]firestore.Update{{Path:"capital",Value:firestore.Delete,},})iferr!=nil{// Handle any errors in an appropriate way, such as returning them.log.Printf("An error has occurred: %s",err)}// ...returnerr}PHP
Use theFieldValue::deleteField() method:
$cityRef = $db->collection('samples/php/cities')->document('BJ');$cityRef->update([ ['path' => 'capital', 'value' => FieldValue::deleteField()]]);Unity
Use theFieldValue.Delete method:
DocumentReferencecityRef=db.Collection("cities").Document("BJ");Dictionary<string,object>updates=newDictionary<string,object>{{"Capital",FieldValue.Delete}};
C#
Use theFieldValue.Delete method:
DocumentReferencecityRef=db.Collection("cities").Document("BJ");Dictionary<string,object>updates=newDictionary<string,object>{{"Capital",FieldValue.Delete}};awaitcityRef.UpdateAsync(updates);Ruby
Use thefirestore.field_delete method:
city_ref=firestore.doc"#{collection_path}/BJ"city_ref.update({capital:firestore.field_delete})Delete collections
To delete an entire collection or subcollection inCloud Firestore,retrieve (read) all the documents within the collection or subcollection and deletethem. This process incurs both read and delete costs. If you have largercollections, you may want to delete the documents in smaller batches to avoidout-of-memory errors. Repeat the process until you've deleted the entirecollection or subcollection.
Deleting a collection requires coordinating an unbounded number ofindividual delete requests. If you need to delete entire collections, do so onlyfrom a trusted server environment. While it is possible to delete a collectionfrom a mobile/web client, doing so has negative security and performance implications.
The following snippets are simplified for clarity and don't include errorhandling, security, deleting subcollections, or performance optimizations. To learn moreabout one recommended approach to deleting collections in production, seeDeleting Collections and Subcollections.
Web
// Deleting collections from a Web client is not recommended.Swift
// Deleting collections from an Apple client is not recommended.Objective-C
// Deleting collections from an Apple client is not recommended.Kotlin
// Deleting collections from an Android client is not recommended.Java
// Deleting collections from an Android client is not recommended.Dart
Deleting collections from the client is not recommended.
Java
/** * Delete a collection in batches to avoid out-of-memory errors. Batch size may be tuned based on * document size (atmost 1MB) and application requirements. */voiddeleteCollection(CollectionReferencecollection,intbatchSize){try{// retrieve a small batch of documents to avoid out-of-memory errorsApiFuture<QuerySnapshot>future=collection.limit(batchSize).get();intdeleted=0;// future.get() blocks on document retrievalList<QueryDocumentSnapshot>documents=future.get().getDocuments();for(QueryDocumentSnapshotdocument:documents){document.getReference().delete();++deleted;}if(deleted>=batchSize){// retrieve and delete another batchdeleteCollection(collection,batchSize);}}catch(Exceptione){System.err.println("Error deleting collection : "+e.getMessage());}}Python
defdelete_collection(coll_ref):print(f"Recursively deleting collection:{coll_ref}")db.recursive_delete(coll_ref)Python
asyncdefdelete_collection(coll_ref):awaitdb.recursive_delete(coll_ref)C++
// This is not supported. Delete data using CLI as discussed below.Node.js
asyncfunctiondeleteCollection(db,collectionPath){constcollectionRef=db.collection(collectionPath);returnawaitdb.recursiveDelete(collectionRef);}Go
import("context""fmt""io""cloud.google.com/go/firestore""google.golang.org/api/iterator")funcdeleteCollection(wio.Writer,projectID,collectionNamestring,batchSizeint)error{// Instantiate a clientctx:=context.Background()client,err:=firestore.NewClient(ctx,projectID)iferr!=nil{returnerr}col:=client.Collection(collectionName)bulkwriter:=client.BulkWriter(ctx)for{// Get a batch of documentsiter:=col.Limit(batchSize).Documents(ctx)numDeleted:=0// Iterate through the documents, adding// a delete operation for each one to the BulkWriter.for{doc,err:=iter.Next()iferr==iterator.Done{break}iferr!=nil{returnerr}bulkwriter.Delete(doc.Ref)numDeleted++}// If there are no documents to delete,// the process is over.ifnumDeleted==0{bulkwriter.End()break}bulkwriter.Flush()}fmt.Fprintf(w,"Deleted collection \"%s\"",collectionName)returnnil}PHP
function data_delete_collection(string $projectId, string $collectionName, int $batchSize){ // Create the Cloud Firestore client $db = new FirestoreClient([ 'projectId' => $projectId, ]); $collectionReference = $db->collection($collectionName); $documents = $collectionReference->limit($batchSize)->documents(); while (!$documents->isEmpty()) { foreach ($documents as $document) { printf('Deleting document %s' . PHP_EOL, $document->id()); $document->reference()->delete(); } $documents = $collectionReference->limit($batchSize)->documents(); }}Unity
// This is not supported. Delete data using CLI as discussed below.C#
privatestaticasyncTaskDeleteCollection(CollectionReferencecollectionReference,intbatchSize){QuerySnapshotsnapshot=awaitcollectionReference.Limit(batchSize).GetSnapshotAsync();IReadOnlyList<DocumentSnapshot>documents=snapshot.Documents;while(documents.Count >0){foreach(DocumentSnapshotdocumentindocuments){Console.WriteLine("Deleting document {0}",document.Id);awaitdocument.Reference.DeleteAsync();}snapshot=awaitcollectionReference.Limit(batchSize).GetSnapshotAsync();documents=snapshot.Documents;}Console.WriteLine("Finished deleting all documents from the collection.");}Ruby
cities_ref=firestore.colcollection_pathquery=cities_refquery.getdo|document_snapshot|puts"Deleting document#{document_snapshot.document_id}."document_ref=document_snapshot.refdocument_ref.deleteendDelete data with TTL policies
A TTL policy designates a given field as the expiration time for documents in agiven collection group. TTL delete operations count towards your document deletecosts.
For information about setting TTL, seeManage data retention with TTL policies.
Bulk deletion jobs
Cloud Firestore supports several tools for bulk deletion. You shouldselect a tool based on the number of documents you need to delete and thelevel of configurability you need.
Note: Deleting a large number of documentscan impact latency.If latency is caused by too many recent deletes, the issue should automaticallyresolve after some time. If the issue does not resolve,contact support.For smaller jobsof thousands of documents, use the console or the Firebase CLI. For largerjobs, these tools might start to timeout and require you to run the tool multipletimes.
Console
You candelete documents and collections from theCloud Firestore page in the console. Deleting a document from theconsole deletes all of the nested data in that document, including anysubcollections.
Firebase CLI
You can also use theFirebase CLIto delete documents and collections. Use the following command to deletedata:
Note: Deleting data with the Firebase CLI incurs read and delete costs.For more information, seePricing.firebase firestore:delete --database=DATABASE_IDPATHReplaceDATABASE_ID with your database ID andPATH with a path to a document or collection.
For large deletion jobs (millions of documents), use one of the following:
Managed bulk delete
Cloud Firestore supports bulk deleting one or more collection groups.For more information, seeBulk delete data.
Dataflow connector
You can useDataflowfor bulk operations on your database. This option is the most configurable,but also requires more set up than other bulk delete options.See theCloud Firestore connector forDataflow introductionblog posthas an example of deleting all documents in a collection group.
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2026-02-18 UTC.