16

I am not sure how to start/accomplish this, I am want the documents in a collection in a firestore database to delete themselves if the document was not changed or accessed for a certain time period (for example 30 days). In other words, the data should expire (be removed) if not needed.

Is there any way to accomplish this task?

Thank you for your help!

jonasxd360
  • 1,225
  • 4
  • 19
  • 35
  • 3
    Use some scheduling mechanism (e.g. cron-job.org) to ping a Cloud Function that queries for documents that are expires, then deletes them. – Doug Stevenson Jun 20 '18 at 16:19

1 Answers1

19

Since late 2022 Firestore supports configuring a time-to-live policy on collections. See the documentation on managing data retention with TTL policies for full details.

I left my previous answer below, just in case somebody wants to roll their own solution.


The below is outdated, and just left for reference. For the latest, see

There is no built-in time-to-live mechanism in Cloud Firestore. The common approach is to run a piece of code at an interval, e.g. a Cloud Function triggered by something like cron-job.org.

Have a look at these questions for samples:

While these are for the Firebase Realtime Database, the same approach applies to Cloud Firestore.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • I would have to change the timestamp each time the document is accessed, right? (to make sure that if the data is still used it will not be deleted) – jonasxd360 Jun 20 '18 at 16:32
  • 1
    Ah, I missed the part about them being accessed. Yes, that would indeed require that you update a timestamp on every read. You can either do that from each client, or by wrapping all client access in Cloud Functions. Sounds like quite some overhead though, so make sure your use-case is worth it. – Frank van Puffelen Jun 20 '18 at 17:07
  • 2
    There's this now: https://firebase.google.com/docs/firestore/ttl – thdoan Dec 05 '22 at 23:46