В следующих примерах показано, как удалять документы, поля и коллекции.
Удалить документы
Чтобы удалить документ, используйте метод 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); });
Быстрый
db.collection("cities").document("DC").delete() { err in if let err = err { print("Error removing document: \(err)") } else { print("Document successfully removed!") } }
Цель-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
С++
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
Идти
PHP
$db->collection('samples/php/cities')->document('DC')->delete();
Единство
DocumentReference cityRef = db.Collection("cities").Document("DC"); cityRef.DeleteAsync();
С#
DocumentReference cityRef = db.Collection("cities").Document("DC"); await cityRef.DeleteAsync();
Рубин
Когда вы удаляете документ, Cloud Firestore не удаляет автоматически документы в своих подколлекциях. Вы по-прежнему можете получить доступ к документам подколлекции по ссылке. Например, вы можете получить доступ к документу по пути /mycoll/mydoc/mysubcoll/mysubdoc
даже если вы удалите исходный документ по пути /mycoll/mydoc
.
Несуществующие документы-предки отображаются в консоли , но не отображаются в результатах запросов и моментальных снимках.
Если вы хотите удалить документ и все документы в его подколлекциях, вы должны сделать это вручную. Дополнительные сведения см. в разделе Удаление коллекций .
Удалить поля
Чтобы удалить определенные поля из документа, используйте метод 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() });
Быстрый
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") } }
Цель-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
С++
DocumentReference doc_ref = db->Collection("cities").Document("BJ"); doc_ref.Update({{"capital", FieldValue::Delete()}}) .OnCompletion([](const Future<void>& future) { /*...*/ });
Node.js
Идти
PHP
$cityRef = $db->collection('samples/php/cities')->document('BJ'); $cityRef->update([ ['path' => 'capital', 'value' => FieldValue::deleteField()] ]);
Единство
DocumentReference cityRef = db.Collection("cities").Document("BJ"); Dictionary<string, object> updates = new Dictionary<string, object> { { "Capital", FieldValue.Delete } };
С#
DocumentReference cityRef = db.Collection("cities").Document("BJ"); Dictionary<string, object> updates = new Dictionary<string, object> { { "Capital", FieldValue.Delete } }; await cityRef.UpdateAsync(updates);
Рубин
Удалить коллекции
Чтобы удалить всю коллекцию или подколлекцию в Cloud Firestore, извлеките все документы в коллекции или подколлекции и удалите их. Если у вас есть большие коллекции, вы можете удалить документы небольшими партиями, чтобы избежать ошибок нехватки памяти. Повторяйте процесс, пока не удалите всю коллекцию или подколлекцию.
Удаление коллекции требует согласования неограниченного количества отдельных запросов на удаление. Если вам нужно удалить целые коллекции, делайте это только из среды доверенного сервера. Хотя коллекцию можно удалить из мобильного/веб-клиента, это отрицательно сказывается на безопасности и производительности.
Приведенные ниже фрагменты несколько упрощены и не касаются обработки ошибок, безопасности, удаления вложенных коллекций или повышения производительности. Дополнительные сведения об одном рекомендуемом подходе к удалению коллекций в рабочей среде см. в разделе Удаление коллекций и вложенных коллекций .
Интернет
// Deleting collections from a Web client is not recommended.
Быстрый
// Deleting collections from an Apple client is not recommended.
Цель-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
С++
// This is not supported. Delete data using CLI as discussed below.
Node.js
Идти
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(); } }
Единство
// This is not supported. Delete data using CLI as discussed below.
С#
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."); }
Рубин
Удалить данные с помощью интерфейса командной строки Firebase
Вы также можете использовать интерфейс командной строки Firebase для удаления документов и коллекций. Используйте следующую команду для удаления данных:
firebase firestore:delete [options] <<path>>
Удалить данные с помощью консоли
Вы можете удалять документы и коллекции со страницы Cloud Firestore в консоли . При удалении документа из консоли удаляются все вложенные данные в этом документе, включая все вложенные коллекции.