Skip to content

Instantly share code, notes, and snippets.

@fforbeck
Last active December 17, 2015 16:09
Show Gist options
  • Save fforbeck/5636702 to your computer and use it in GitHub Desktop.
Save fforbeck/5636702 to your computer and use it in GitHub Desktop.
Activating MongoDB TTL for indexes
- Creating new index with ttl, the key must be date type and can not be a compound index.
> db.teste_ttl_idx.ensureIndex({ttl: 1}, {expireAfterSeconds: 5});
- Insert new documents
> db.teste_ttl_idx.insert({ttl: new Date()});
> db.teste_ttl_idx.insert({ttl: new Date()});
> db.teste_ttl_idx.insert({ttl: new Date()});
- You can do a find all to check if the elements were inserted and if they will be removed in the next 5 seconds after their creation.
> db.teste_ttl_idx.find();
Note:
- TTL indexes expire data by removing documents in a background task that runs every 60 seconds. As a result, the TTL index provides no guarantees that expired documents will not exist in the collection. Consider that:
Documents may remain in a collection after they expire and before the background process runs.
The duration of the removal operations depend on the workload of your mongod instance.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment