本頁面由 Cloud Translation API 翻譯而成。
Switch to English

從Cloud Firestore刪除數據

下面的示例演示如何刪除文檔,字段和集合。

刪除文件

要刪除文檔,請使用delete()方法:

網頁
db.collection("cities").doc("DC").delete().then(function() {
    console.log("Document successfully deleted!");
}).catch(function(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!");
      }
}];
  

爪哇

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) }
爪哇
// asynchronously delete a document
ApiFuture<WriteResult> writeResult = db.collection("cities").document("DC").delete();
// ...
System.out.println("Update time : " + writeResult.get().getUpdateTime());
蟒蛇
db.collection(u'cities').document(u'DC').delete()
C ++
db->Collection("cities").Document("DC").Delete().OnCompletion(
    [](const Future<void>& future) {
      if (future.error() == Error::kErrorOk) {
        std::cout << "DocumentSnapshot successfully deleted!\n";
      } else {
        std::cout << "Error deleting document: " << future.error_message()
                  << '\n';
      }
    });
  
Node.js
const res = await db.collection('cities').doc('DC').delete();
_, 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)
}
的PHP
$db->collection('cities')->document('DC')->delete();
統一
DocumentReference cityRef = db.Collection("cities").Document("DC");
cityRef.DeleteAsync();
C#
DocumentReference cityRef = db.Collection("cities").Document("DC");
await cityRef.DeleteAsync();
紅寶石
city_ref = firestore.doc "cities/DC"
city_ref.delete

刪除文檔時,Cloud Firestore不會自動刪除其子集合中的文檔。您仍然可以通過引用訪問子集合文檔。例如,即使您刪除了/mycoll/mydoc的祖先文檔,您也可以訪問路徑/mycoll/mydoc/mysubcoll/mysubdoc的文檔。

不存在的祖先文檔顯示在控制台中 ,但不會出現在查詢結果和快照中。

如果要刪除文檔及其子集合中的所有文檔,則必須手動刪除。有關更多信息,請參見刪除集合

刪除欄位

要從文檔中刪除特定字段,請在更新文檔時使用FieldValue.delete()方法:

網頁
a7b5ae5​​652
迅速
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");
  }
}];
  

爪哇

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 { }
爪哇
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());
蟒蛇
city_ref = db.collection(u'cities').document(u'BJ')
city_ref.update({
    u'capital': firestore.DELETE_FIELD
})
C ++
DocumentReference doc_ref = db->Collection("cities").Document("BJ");
doc_ref.Update({{"capital", FieldValue::Delete()}})
    .OnCompletion([](const Future<void>& future) { /*...*/ });
  
Node.js
// Get the `FieldValue` object
const FieldValue = admin.firestore.FieldValue;

// 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()
});
_, 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)
}
的PHP
$cityRef = $db->collection('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 }
};
C#
第064章
紅寶石
city_ref = firestore.doc "cities/BJ"
city_ref.update capital: firestore.field_delete

刪除收藏

要在Cloud Firestore中刪除整個集合或子集合,請檢索集合或子集合中的所有文檔並將其刪除。如果您有較大的館藏,則可能要分批刪除文檔,以避免內存不足的錯誤。重複該過程,直到您刪除了整個集合或子集合。

刪除集合需要協調無數個單獨的刪除請求。如果需要刪除整個集合,請僅從受信任的服務器環境中刪除。儘管可以從移動/ Web客戶端刪除集合,但是這樣做會對安全性和性能造成負面影響。

下面的代碼片段經過了一些簡化,它們不涉及錯誤處理,安全性,刪除子集合或最大化性能。要了解有關在生產環境中刪除收藏夾的一種推薦方法的更多信息,請參閱《 刪除收藏夾和子收藏夾》

網頁
// Deleting collections from a Web client is not recommended.
迅速
// Deleting collections from an iOS client is not recommended.
目標C
// Deleting collections from an iOS client is not recommended.
  

爪哇

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

Kotlin + KTX

// Deleting collections from an Android client is not recommended.
爪哇
/** 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());
  }
}
蟒蛇
def delete_collection(coll_ref, batch_size):
    docs = coll_ref.limit(batch_size).stream()
    deleted = 0

    for doc in docs:
        print(f'Deleting doc {doc.id} => {doc.to_dict()}')
        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);
  });
}

func deleteCollection(ctx context.Context, client *firestore.Client,
	ref *firestore.CollectionRef, batchSize int) error {

	for {
		// Get a batch of documents
		iter := ref.Limit(batchSize).Documents(ctx)
		numDeleted := 0

		// Iterate through the documents, adding
		// a delete operation for each one to a
		// WriteBatch.
		batch := client.Batch()
		for {
			doc, err := iter.Next()
			if err == iterator.Done {
				break
			}
			if err != nil {
				return err
			}

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

		// If there are no documents to delete,
		// the process is over.
		if numDeleted == 0 {
			return nil
		}

		_, err := batch.Commit(ctx)
		if err != nil {
			return err
		}
	}
}

的PHP
function delete_collection($collectionReference, $batchSize)
{
    $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.
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.");
}
紅寶石
cities_ref = firestore.col "cities"
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頁面中刪除文檔和集合 。從控制台刪除文檔會刪除該文檔中的所有嵌套數據,包括所有子集合。