次の例は、ドキュメント、フィールド、コレクションを削除する方法を示しています。
ドキュメントを削除する
ドキュメントを削除するには、delete()
メソッドを使用します。
ウェブ バージョン 9
import { doc, deleteDoc } from "firebase/firestore"; await deleteDoc(doc(db, "cities", "DC"));
Web バージョン 8
db.collection("cities").doc("DC").delete().then(() => { console.log("Document successfully deleted!"); }).catch((error) => { console.error("Error removing document: ", error); });
Swift
db.collection("cities").document("DC").delete() { err in if let err = err { print("Error removing document: \(err)") } else { print("Document successfully removed!") } }
Objective-C
[[[self.db collectionWithPath:@"cities"] documentWithPath:@"DC"] deleteDocumentWithCompletion:^(NSError * _Nullable error) { if (error != nil) { NSLog(@"Error removing document: %@", error); } else { NSLog(@"Document successfully removed!"); } }];
Java
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); } });
Kotlin+KTX
db.collection("cities").document("DC") .delete() .addOnSuccessListener { Log.d(TAG, "DocumentSnapshot successfully deleted!") } .addOnFailureListener { e -> Log.w(TAG, "Error deleting document", e) }
Java
Python
Python
C++
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
Go
PHP
$db->collection('samples/php/cities')->document('DC')->delete();
Unity
DocumentReference cityRef = db.Collection("cities").Document("DC"); cityRef.DeleteAsync();
C#
DocumentReference cityRef = db.Collection("cities").Document("DC"); await cityRef.DeleteAsync();
Ruby
ドキュメントを削除しても、Cloud Firestore はサブコレクション内のドキュメントを自動的には削除しません。サブコレクションのドキュメントには参照により引き続きアクセスできます。たとえば、パス /mycoll/mydoc/mysubcoll/mysubdoc
にあるドキュメントには、/mycoll/mydoc
の祖先ドキュメントを削除してもアクセスできます。
存在しない祖先ドキュメントはコンソールには表示されますが、クエリの結果やスナップショットには表示されません。
ドキュメントと、そのドキュメントのサブコレクション内のすべてのドキュメントを削除するには、手動での操作が必要です。詳しくは、コレクションを削除するをご覧ください。
フィールドを削除する
特定のフィールドをドキュメントから削除するには、ドキュメントを更新するときに FieldValue.delete()
メソッドを使用します。
ウェブ バージョン 9
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 バージョン 8
var cityRef = db.collection('cities').doc('BJ'); // Remove the 'capital' field from the document var removeCapital = cityRef.update({ capital: firebase.firestore.FieldValue.delete() });
Swift
db.collection("cities").document("BJ").updateData([ "capital": FieldValue.delete(), ]) { err in if let err = err { print("Error updating document: \(err)") } else { print("Document successfully updated") } }
Objective-C
[[[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"); } }];
Java
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>() { // ... // ...
Kotlin+KTX
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
Python
Python
C++
DocumentReference doc_ref = db->Collection("cities").Document("BJ"); doc_ref.Update({{"capital", FieldValue::Delete()}}) .OnCompletion([](const Future<void>& future) { /*...*/ });
Node.js
Go
PHP
$cityRef = $db->collection('samples/php/cities')->document('BJ'); $cityRef->update([ ['path' => 'capital', 'value' => FieldValue::deleteField()] ]);
Unity
DocumentReference cityRef = db.Collection("cities").Document("BJ"); Dictionary<string, object> updates = new Dictionary<string, object> { { "Capital", FieldValue.Delete } };
C#
DocumentReference cityRef = db.Collection("cities").Document("BJ"); Dictionary<string, object> updates = new Dictionary<string, object> { { "Capital", FieldValue.Delete } }; await cityRef.UpdateAsync(updates);
Ruby
コレクションを削除する
Cloud Firestore でコレクション全体またはサブコレクションを削除するには、コレクションまたはサブコレクション内のすべてのドキュメントを取得して削除します。大きなコレクションがある場合は、メモリ不足エラーを避けるため、小さなバッチに分けてドキュメントを削除することをおすすめします。コレクション全体またはサブコレクションが削除されるまで、このプロセスを繰り返します。
コレクションを削除するには、数に制約のない個別の削除リクエストを用意する必要があります。コレクション全体を削除する必要がある場合は、信頼できるサーバー環境からのみ実行してください。モバイル / ウェブ クライアントからコレクションを削除することも可能ですが、その場合セキュリティとパフォーマンスに悪影響を与えます。
以下のスニペットは少し単純化されていて、エラー処理、セキュリティ、サブコレクションの削除、またはパフォーマンスの最大化については扱っていません。本番環境でコレクションを削除するために推奨される方法については、コレクションとサブコレクションを削除するをご覧ください。
ウェブ
// 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.
Java
// Deleting collections from an Android client is not recommended.
Kotlin+KTX
// Deleting collections from an Android client is not recommended.
Java
Python
Python
C++
// This is not supported. Delete data using CLI as discussed below.
Node.js
Go
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
Firebase CLI でデータを削除する
Firebase CLI を使用して、ドキュメントやコレクションを削除することもできます。データを削除するには、次のコマンドを使用します。
firebase firestore:delete [options] <<path>>
コンソールでデータを削除する
ドキュメントやコレクションの削除は、コンソールの Cloud Firestore ページから行います。コンソールからドキュメントを削除すると、サブコレクションを含むそのドキュメント内のネストされたデータがすべて削除されます。