Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoid document Time to Live

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.

like image 874
Seif Sallam Avatar asked Feb 04 '13 10:02

Seif Sallam


People also ask

What is time to live in MongoDB?

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.

How to set TTL in MongoDB?

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.

What is a time to live index?

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.


1 Answers

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
like image 142
wyattisimo Avatar answered Oct 21 '22 16:10

wyattisimo