刪除 Cloud Firestore 中的資料

以下範例說明如何刪除文件、欄位和集合。

刪除文件

如要刪除文件,請使用下列特定語言的 delete() 方法:

Web

使用 deleteDoc() 方法:

import { doc, deleteDoc } from "firebase/firestore";

await deleteDoc(doc(db, "cities", "DC"));

Web

使用 delete() 方法:

db.collection("cities").doc("DC").delete().then(() => {
    console.log("Document successfully deleted!");
}).catch((error) => {
    console.error("Error removing document: ", error);
});
Swift

使用 delete() 方法:

注意:這項產品不適用於 watchOS 和 App Clip 目標。
do {
  try await db.collection("cities").document("DC").delete()
  print("Document successfully removed!")
} catch {
  print("Error removing document: \(error)")
}
Objective-C

使用 deleteDocumentWithCompletion: 方法:

注意:這項產品不適用於 watchOS 和 App Clip 目標。
[[[self.db collectionWithPath:@"cities"] documentWithPath:@"DC"]
    deleteDocumentWithCompletion:^(NSError * _Nullable error) {
      if (error != nil) {
        NSLog(@"Error removing document: %@", error);
      } else {
        NSLog(@"Document successfully removed!");
      }
}];

Kotlin+KTX

使用 delete() 方法:

db.collection("cities").document("DC")
    .delete()
    .addOnSuccessListener { Log.d(TAG, "DocumentSnapshot successfully deleted!") }
    .addOnFailureListener { e -> Log.w(TAG, "Error deleting document", e) }

Java

使用 delete() 方法:

db.collection("cities").document("DC")
        .delete()
        .addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Log.d(TAG, "DocumentSnapshot successfully deleted!");
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.w(TAG, "Error deleting document", e);
            }
        });

Dart

使用 delete() 方法:

db.collection("cities").doc("DC").delete().then(
      (doc) => print("Document deleted"),
      onError: (e) => print("Error updating document $e"),
    );
Java

使用 delete() 方法:

// asynchronously delete a document
ApiFuture<WriteResult> writeResult = db.collection("cities").document("DC").delete();
// ...
System.out.println("Update time : " + writeResult.get().getUpdateTime());
Python

使用 delete() 方法:

db.collection("cities").document("DC").delete()

Python

使用 delete() 方法:

await db.collection("cities").document("DC").delete()
C++

使用 Delete() 方法:

db->Collection("cities").Document("DC").Delete().OnCompletion(
    [](const Future<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

使用 delete() 方法:

const res = await db.collection('cities').doc('DC').delete();
Go

使用 Delete() 方法:


import (
	"context"
	"log"

	"cloud.google.com/go/firestore"
)

func deleteDoc(ctx context.Context, client *firestore.Client) error {
	_, err := client.Collection("cities").Doc("DC").Delete(ctx)
	if err != nil {
		// Handle any errors in an appropriate way, such as returning them.
		log.Printf("An error has occurred: %s", err)
	}

	return err
}
PHP

使用 delete() 方法:

$db->collection('samples/php/cities')->document('DC')->delete();
Unity

使用 DeleteAsync() 方法:

DocumentReference cityRef = db.Collection("cities").Document("DC");
cityRef.DeleteAsync();
C#

使用 DeleteAsync() 方法:

DocumentReference cityRef = db.Collection("cities").Document("DC");
await cityRef.DeleteAsync();
Ruby

使用 delete() 方法:

city_ref = firestore.doc "#{collection_path}/DC"
city_ref.delete

刪除文件時,Cloud Firestore 不會自動刪除其子集合中的文件。您仍可透過參照存取子集合文件。舉例來說,即使您刪除 /mycoll/mydoc 中的祖系文件,還是可以存取 /mycoll/mydoc/mysubcoll/mysubdoc 路徑中的文件。

不存在的祖系文件會顯示在控制台,但不會顯示在查詢結果和快照中。

如果您想刪除文件及其子集合中的所有文件,必須手動執行這項操作。詳情請參閱「刪除集合」。

刪除欄位

如要從文件中刪除特定欄位,請在更新文件時使用下列特定語言的 FieldValue.delete() 方法:

Web

使用 deleteField() 方法:

import { doc, updateDoc, deleteField } from "firebase/firestore";

const cityRef = doc(db, 'cities', 'BJ');

// Remove the 'capital' field from the document
await updateDoc(cityRef, {
    capital: deleteField()
});

Web

使用 FieldValue.delete() 方法:

var cityRef = db.collection('cities').doc('BJ');

// Remove the 'capital' field from the document
var removeCapital = cityRef.update({
    capital: firebase.firestore.FieldValue.delete()
});
Swift

使用 FieldValue.delete() 方法:

注意:這項產品不適用於 watchOS 和 App Clip 目標。
do {

  try await db.collection("cities").document("BJ").updateData([
    "capital": FieldValue.delete(),
  ])
  print("Document successfully updated")
} catch {
  print("Error updating document: \(error)")
}
Objective-C

使用 fieldValueForDelete: 方法:

注意:這項產品不適用於 watchOS 和 App Clip 目標。
[[[self.db collectionWithPath:@"cities"] documentWithPath:@"BJ"] updateData:@{
  @"capital": [FIRFieldValue fieldValueForDelete]
} completion:^(NSError * _Nullable error) {
  if (error != nil) {
    NSLog(@"Error updating document: %@", error);
  } else {
    NSLog(@"Document successfully updated");
  }
}];

Kotlin+KTX

使用 FieldValue.delete() 方法:

val docRef = db.collection("cities").document("BJ")

// Remove the 'capital' field from the document
val updates = hashMapOf<String, Any>(
    "capital" to FieldValue.delete(),
)

docRef.update(updates).addOnCompleteListener { }

Java

使用 FieldValue.delete() 方法:

DocumentReference docRef = db.collection("cities").document("BJ");

// Remove the 'capital' field from the document
Map<String,Object> updates = new HashMap<>();
updates.put("capital", FieldValue.delete());

docRef.update(updates).addOnCompleteListener(new OnCompleteListener<Void>() {
    // ...
    // ...

Dart

使用 FieldValue.delete() 方法:

final docRef = db.collection("cities").doc("BJ");

// Remove the 'capital' field from the document
final updates = <String, dynamic>{
  "capital": FieldValue.delete(),
};

docRef.update(updates);
Java

使用 FieldValue.delete() 方法:

DocumentReference docRef = db.collection("cities").document("BJ");
Map<String, Object> updates = new HashMap<>();
updates.put("capital", FieldValue.delete());
// Update and delete the "capital" field in the document
ApiFuture<WriteResult> writeResult = docRef.update(updates);
System.out.println("Update time : " + writeResult.get());
Python

使用 firestore.DELETE_FIELD 方法:

city_ref = db.collection("cities").document("BJ")
city_ref.update({"capital": firestore.DELETE_FIELD})

Python

使用 firestore.DELETE_FIELD 方法:

city_ref = db.collection("cities").document("BJ")
await city_ref.update({"capital": firestore.DELETE_FIELD})
C++

使用 FieldValue::Delete() 方法:

DocumentReference doc_ref = db->Collection("cities").Document("BJ");
doc_ref.Update({{"capital", FieldValue::Delete()}})
    .OnCompletion([](const Future<void>& future) { /*...*/ });
Node.js

使用 FieldValue.delete() 方法:

// Create a document reference
const cityRef = db.collection('cities').doc('BJ');

// Remove the 'capital' field from the document
const res = await cityRef.update({
  capital: FieldValue.delete()
});
Go

使用 firestore.Delete 方法:


import (
	"context"
	"log"

	"cloud.google.com/go/firestore"
)

func deleteField(ctx context.Context, client *firestore.Client) error {
	_, err := client.Collection("cities").Doc("BJ").Update(ctx, []firestore.Update{
		{
			Path:  "capital",
			Value: firestore.Delete,
		},
	})
	if err != nil {
		// Handle any errors in an appropriate way, such as returning them.
		log.Printf("An error has occurred: %s", err)
	}

	// ...
	return err
}
PHP

使用 FieldValue::deleteField() 方法:

$cityRef = $db->collection('samples/php/cities')->document('BJ');
$cityRef->update([
    ['path' => 'capital', 'value' => FieldValue::deleteField()]
]);
Unity

使用 FieldValue.Delete 方法:

DocumentReference cityRef = db.Collection("cities").Document("BJ");
Dictionary<string, object> updates = new Dictionary<string, object>
{
    { "Capital", FieldValue.Delete }
};
C#

使用 FieldValue.Delete 方法:

DocumentReference cityRef = db.Collection("cities").Document("BJ");
Dictionary<string, object> updates = new Dictionary<string, object>
{
    { "Capital", FieldValue.Delete }
};
await cityRef.UpdateAsync(updates);
Ruby

使用 firestore.field_delete 方法:

city_ref = firestore.doc "#{collection_path}/BJ"
city_ref.update({ capital: firestore.field_delete })

刪除集合

如要刪除 Cloud Firestore 中的整個珍藏內容或子集合,請擷取 (讀取) 珍藏內容或子集合中的所有文件,然後刪除這些文件。這項程序會產生讀取和刪除費用。如果您的集合較大,可能會建議以較小的批次刪除文件,以免發生記憶體不足的錯誤。重複執行這個程序,直到刪除整個集合或子集合為止。

刪除集合需要協調不限數量的個別刪除要求。如果您需要刪除整個產品素材資源集合,請務必在可信任的伺服器環境中執行。雖然可以從行動/網頁用戶端刪除集合,但這會對安全性和效能造成負面影響。

下列程式碼片段略為簡化,且不會處理錯誤處理、安全性、刪除子集合或將效能最大化。如要進一步瞭解在正式環境中刪除集合的建議做法,請參閱「刪除集合和子集合」。

網頁
// Deleting collections from a Web client is not recommended.
Swift
注意:這項產品不適用於 watchOS 和 App Clip 目標。
// Deleting collections from an Apple client is not recommended.
Objective-C
注意:這項產品不適用於 watchOS 和 App Clip 目標。
// Deleting collections from an Apple client is not recommended.
  

Kotlin+KTX

// Deleting collections from an Android client is not recommended.

Java

// Deleting collections from an Android client is not recommended.

Dart

我們不建議從用戶端刪除集合。

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.
 */
void deleteCollection(CollectionReference collection, int batchSize) {
  try {
    // retrieve a small batch of documents to avoid out-of-memory errors
    ApiFuture<QuerySnapshot> future = collection.limit(batchSize).get();
    int deleted = 0;
    // future.get() blocks on document retrieval
    List<QueryDocumentSnapshot> documents = future.get().getDocuments();
    for (QueryDocumentSnapshot document : documents) {
      document.getReference().delete();
      ++deleted;
    }
    if (deleted >= batchSize) {
      // retrieve and delete another batch
      deleteCollection(collection, batchSize);
    }
  } catch (Exception e) {
    System.err.println("Error deleting collection : " + e.getMessage());
  }
}
Python
def delete_collection(coll_ref, batch_size):
    if batch_size == 0:
        return

    docs = coll_ref.list_documents(page_size=batch_size)
    deleted = 0

    for doc in docs:
        print(f"Deleting doc {doc.id} => {doc.get().to_dict()}")
        doc.delete()
        deleted = deleted + 1

    if deleted >= batch_size:
        return delete_collection(coll_ref, batch_size)

Python

async def delete_collection(coll_ref, batch_size):
    docs = coll_ref.limit(batch_size).stream()
    deleted = 0

    async for doc in docs:
        print(f"Deleting doc {doc.id} => {doc.to_dict()}")
        await doc.reference.delete()
        deleted = deleted + 1

    if deleted >= batch_size:
        return delete_collection(coll_ref, batch_size)
C++
// This is not supported. Delete data using CLI as discussed below.
  
Node.js
async function deleteCollection(db, collectionPath, batchSize) {
  const collectionRef = db.collection(collectionPath);
  const query = collectionRef.orderBy('__name__').limit(batchSize);

  return new Promise((resolve, reject) => {
    deleteQueryBatch(db, query, resolve).catch(reject);
  });
}

async function deleteQueryBatch(db, query, resolve) {
  const snapshot = await query.get();

  const batchSize = snapshot.size;
  if (batchSize === 0) {
    // When there are no documents left, we are done
    resolve();
    return;
  }

  // Delete documents in a batch
  const batch = db.batch();
  snapshot.docs.forEach((doc) => {
    batch.delete(doc.ref);
  });
  await batch.commit();

  // Recurse on the next process tick, to avoid
  // exploding the stack.
  process.nextTick(() => {
    deleteQueryBatch(db, query, resolve);
  });
}
Go

import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/firestore"
	"google.golang.org/api/iterator"
)

func deleteCollection(w io.Writer, projectID, collectionName string,
	batchSize int) error {

	// Instantiate a client
	ctx := context.Background()
	client, err := firestore.NewClient(ctx, projectID)
	if err != nil {
		return err
	}

	col := client.Collection(collectionName)
	bulkwriter := client.BulkWriter(ctx)

	for {
		// Get a batch of documents
		iter := 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()
			if err == iterator.Done {
				break
			}
			if err != nil {
				return err
			}

			bulkwriter.Delete(doc.Ref)
			numDeleted++
		}

		// If there are no documents to delete,
		// the process is over.
		if numDeleted == 0 {
			bulkwriter.End()
			break
		}

		bulkwriter.Flush()
	}
	fmt.Fprintf(w, "Deleted collection \"%s\"", collectionName)
	return nil
}
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#
private static async Task DeleteCollection(CollectionReference collectionReference, int batchSize)
{
    QuerySnapshot snapshot = await collectionReference.Limit(batchSize).GetSnapshotAsync();
    IReadOnlyList<DocumentSnapshot> documents = snapshot.Documents;
    while (documents.Count > 0)
    {
        foreach (DocumentSnapshot document in documents)
        {
            Console.WriteLine("Deleting document {0}", document.Id);
            await document.Reference.DeleteAsync();
        }
        snapshot = await collectionReference.Limit(batchSize).GetSnapshotAsync();
        documents = snapshot.Documents;
    }
    Console.WriteLine("Finished deleting all documents from the collection.");
}
Ruby
cities_ref = firestore.col collection_path
query      = cities_ref

query.get do |document_snapshot|
  puts "Deleting document #{document_snapshot.document_id}."
  document_ref = document_snapshot.ref
  document_ref.delete
end

使用 Firebase CLI 刪除資料

您也可以使用 Firebase CLI 刪除文件和集合。使用下列指令刪除資料:

firebase firestore:delete [options] <<path>>

使用控制台刪除資料

您可以透過控制台的 Cloud Firestore 頁面刪除文件和集合。從主控台刪除文件也會一併刪除該文件中的所有巢狀資料,包括任何子集合。

使用存留時間政策刪除資料

存留時間政策會將特定欄位指定為特定集合群組中文件的到期時間。TTL 刪除作業會計入文件刪除費用。

如要進一步瞭解如何設定存留時間,請參閱「使用存留時間政策管理資料保留機制」。

如要進一步瞭解錯誤代碼,以及如何解決刪除資料時的延遲問題,請參閱疑難排解頁面

使用 Dataflow 刪除資料

Dataflow 是處理 Firestore 資料庫大量作業的絕佳工具。部落格文章介紹了 Dataflow 的 Firestore 連接器,其中有刪除集合群組中所有文件的範例。

使用受管理的大量刪除功能

Cloud Firestore 可用於大量刪除一或多個集合群組。詳情請參閱「大量刪除資料」。