How do you find expired documents in Cloudant?

Viewed 9

I have documents in Cloudant which contain an expiry date, e.g.

{
  "_id": "a",
  "name": "bob",
  "expiry_date": "2022-06-05"
}

What is the best way to identify documents that have expired to perform some action them, e.g. delete them?

1 Answers

The ideal way in this case is to build a view that emits the expiration date:

function (doc) {
  emit(doc.expiry_date);
}

So then if you want expired documents you can use this view to query the dataset and find documents whose expiry date is before today. You would pass in the following parameters:

  • startkey="0000-00-00" (the beginning of time)
  • endkey="2022-03-16" (today's date)

Your query URL would look something like this:

/<database>/_design/<design_doc_name>/_view/<view_name>?include_docs=true&startkey="0000-00-00"&endkey="2022-03-16"

It would return all the matching documents in expiry_date order

Related