
刪除Firestore 中的集合或子集合
在Firestore 中處理巢狀資料結構時,由於限制,刪除集合可能會很限制棘手集合刪除。本文提供了一種在維護資料結構的同時刪除集合和子集合的解決方案。
在所呈現的場景中,有一個名為「清單」的集合,其中包含具有代表清單 ID 的 ID 的文件。每個清單文件都有兩個子集合:「員工」和「位置」。刪除特定清單需要小心處理,以避免孤立子集合。
刪除過程
要成功刪除特定列表,請按照以下步驟操作:
大型集合的批量刪除
對於大型集合,建議批量刪除文檔,以避免內存錯誤。實作一個功能,批量刪除 10 個文檔,然後重複該過程,直到刪除整個集合。
Firestore 安全影響
需要注意的是,Firebase團隊建議不要刪除集合。但是,對於小型集合和受信任的伺服器環境,可以謹慎使用此方法。
Android 程式碼範例
對於 Android 應用程序,您可以使用以下內容刪除集合的程式碼:
<code class="java">private void deleteCollection(final CollectionReference collection, Executor executor) {
Tasks.call(executor, () -> {
int batchSize = 10;
Query query = collection.orderBy(FieldPath.documentId()).limit(batchSize);
List<DocumentSnapshot> deleted = deleteQueryBatch(query);
while (deleted.size() >= batchSize) {
DocumentSnapshot last = deleted.get(deleted.size() - 1);
query = collection.orderBy(FieldPath.documentId()).startAfter(last.getId()).limit(batchSize);
deleted = deleteQueryBatch(query);
}
return null;
});
}
@WorkerThread
private List<DocumentSnapshot> deleteQueryBatch(final Query query) throws Exception {
QuerySnapshot querySnapshot = Tasks.await(query.get());
WriteBatch batch = query.getFirestore().batch();
for (DocumentSnapshot snapshot : querySnapshot) {
batch.delete(snapshot.getReference());
}
Tasks.await(batch.commit());
return querySnapshot.getDocuments();
}</code>以上是如何在維護資料結構的同時刪除 Firestore 中的集合或子集合?的詳細內容。更多資訊請關注PHP中文網其他相關文章!