Is there a way to set time to live for a document and then it gets destroyed. I want to create guest users that are temporary per session, so after a week the document gets removed automatically.
Time-to-live (TTL) functionality allows the database to automatically expire data. Azure Cosmos DB's API for MongoDB utilizes Cosmos DB's core TTL capabilities. Two modes are supported: setting a default TTL value on the whole collection, and setting individual TTL values for each document.
You can just create a TTL index on scheduledDate , if the value is zero it will not be deleted. According to the documentation, if the indexed field in a document is not a date or an array that holds a date value(s), the document will not expire.
TTL indexes are special single-field indexes that MongoDB can use to automatically remove documents from a collection after a certain amount of time or at a specific clock time.
MongoDB (version 2.2 and up) actually has a special index type that allows you to specify a TTL on a document (see http://docs.mongodb.org/manual/tutorial/expire-data/). The database removes expired documents for you--no need for cron jobs or anything.
Mongoid supports this feature as follows:
index({created_at: 1}, {expire_after_seconds: 1.week})
The created_at
field must hold date/time information. Include Mongoid::Timestamps
in your model to get that for free.
UPDATE:
If you want to expire only a subset of documents, then you can create a special date/time field that is only populated for that subset. Documents with no value or a non-date/time value in the indexed field will never expire. For example:
# Special date/time field to base expirations on.
field :expirable_created_at, type: Time
# TTL index on the above field.
index({expirable_created_at: 1}, {expire_after_seconds: 1.week})
# Callback to set `expirable_created_at` only for guest roles.
before_create :set_expire, if: "role == :guest"
def set_expire
self.expirable_created_at = Time.now
return true
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With