Jitendera Kumar
Jitendera Kumar

Reputation: 139

How to delete a collection with all its sub-collections and documents from Cloud Firestore

I have a Collection in Cloud Firestore and it has millions of documents and sub-collections. I want to delete this collection with all its documents and sub-collection. We can do this from Firebase console but that will take ages to delete this collection.

Is there any firebase cli command or node.js code snippet by using I can delete this collection?

Upvotes: 1

Views: 297

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

The Firebase CLI has a firestore:delete command that recursively deletes content too. See its documentation here.

Note that neither the API nor the CLI are likely to be significantly faster than the console. Since there is no API to bulk-delete data, they all are essentially taking the same approach.

Upvotes: 1

ThienLD
ThienLD

Reputation: 741

You can delete a collection by deleting all its documents. You can read more in the official docs. Example code here:

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);
  });
}

In case the answer above is not working, you can use Cloud Functions as in here

Upvotes: 1

Related Questions