This project has moved and is read-only. For the latest updates, please go here.

Possible to set TTL?

Sep 5, 2014 at 5:39 PM
Firstly, I'm new to MongoDB so please forgive me if I'm not asking this properly.

Is it possible using MongoRepository to create a TTL collection?

I have an Entity with a DateTime property that I'd like to use as an Expiration date. I've looked through CollectionOptions and MongoRepositoryManager<T> but I haven't found anything seems to accomplish this (however it's highly possible I just missed it).

Sep 5, 2014 at 8:28 PM
You should inherit from MongoRepository<YourEntity> and simply re-implement some methods as follows (pseudo-code):
public override T GetById(string id) {
  //Get entity
  var e = base.GetById(id);
  //See if it has expired
  if (IsExpiredByTTL(e.SomeProperty))
    return null;  //It has expired. We return null (or throw an exception or...)
  //Return entity
  return e;
It's not MongoRepository's responsibility to implement a TTL mechanism. MongoRepository is merely an implementation of an IRepository pattern; it provides a framework/pattern to implement repositories. Any Mongo-specific details are abstracted (e.g. "hidden") away as much as possible.
Sep 5, 2014 at 9:12 PM
Thanks for the quick reply. I think I was still fuzzy about the boundaries between MongRepository and the Mongo API.

I was trying to ask about Mongo's built-in TTL support (, without understanding how the Mongo specific stuff was exposed through MongoRepository.

At any rate, I was able to get it working with the following code (for anyone else that may be confused as I was):
public class MyRepository : MongoRepository<MyEntity>
    public MyRepository()
        //Tell Mongo to delete entities one hour after they expire
        var index = new IndexKeysBuilder<MyEntity>().Ascending(e => e.ExpirationDate);
        var options = IndexOptions.SetTimeToLive(TimeSpan.FromHours(1));

        this.collection.EnsureIndex(index, options);
Thanks for the project. It really made it effortless to get up and running with Mongo.