다음 예시는 문서, 필드, 컬렉션을 삭제하는 방법을 보여줍니다.
문서 삭제
문서를 삭제하려면 delete()
메서드를 사용합니다.
Web version 9
import { doc, deleteDoc } from "firebase/firestore"; await deleteDoc(doc(db, "cities", "DC"));
Web version 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) }
Dart
db.collection("cities").doc("DC").delete().then( (doc) => print("Document deleted"), onError: (e) => print("Error updating document $e"), );
자바
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
에서 상위 문서를 삭제했더라도 /mycoll/mydoc/mysubcoll/mysubdoc
경로에 있는 문서에 액세스할 수 있습니다.
존재하지 않는 상위 문서는 콘솔에 표시되지만 쿼리나 스냅샷에는 표시되지 않습니다.
문서를 삭제할 때 하위 컬렉션의 문서까지 삭제하려면 수동으로 삭제해야 합니다. 자세한 내용은 컬렉션 삭제를 참조하세요.
필드 삭제
문서에서 특정 필드를 삭제하려면 문서를 업데이트할 때 FieldValue.delete()
메서드를 사용합니다.
Web version 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 version 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 { }
Dart
final docRef = db.collection("cities").doc("BJ"); // Remove the 'capital' field from the document final updates = <String, dynamic>{ "capital": FieldValue.delete(), }; docRef.update(updates);
자바
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.
Dart
컬렉션은 클라이언트에서 삭제하지 않는 것이 좋습니다.
자바
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 페이지에서 문서 및 컬렉션을 삭제할 수 있습니다. 콘솔에서 문서를 삭제하면 하위 컬렉션을 포함하여 해당 문서의 중첩된 데이터가 모두 삭제됩니다.