Search code examples
c#mongodb

How to Set TTL in MongoDB uing C# MongoDriver


I am using MongoDb in c# . I insert a Student Like below

_client = new MongoClient(new MongoClientSettings
{
    Server = new MongoServerAddress("172.1.9.8", 27017)
});
_database = _client.GetDatabase("MongoSample");

Student st = new Student()
{
    Name = "Ali",
    Family = "Valid",
    Age = 25,
    expireAt = DateTime.Now.AddSeconds(30)
};
var collection = _database.GetCollection<Student>("Students");
collection.InsertOne(st);

I want to set a TTL to Remove data after some seconds , I try to do that like this :

var collection = _database.GetCollection<Student>("Students");
var indexs = collection.Indexes.CreateOne(Builders<Student>.IndexKeys.Ascending("Name"),
            new CreateIndexOptions { ExpireAfter = new TimeSpan(0, 0, 10) });

collection.InsertOne(st);

but it does not work. my model is :

public class Student
{
    public string Name { get; set; }
    public string Family { get; set; }
    public int Age { get; set; }
    [BsonElement("expireAt")]
    public DateTime expireAt { get; set; }
}

Note : and I have problem with DateTime , stored data in db is different with Set Date in Visual Studio


Solution

  • After reading Mongodb documents again , there was a mistake in my code to add Index . there some restriction to work TTL .

    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.

    I'v tried to set Index on Name and it does not contain Date.

    below code works fine .

    var indexKeysDefinition = Builders<Student>.IndexKeys.Ascending("expireAt");
    var indexOptions = new CreateIndexOptions { ExpireAfter = new TimeSpan(0, 0, 60) };
    var indexModel = new CreateIndexModel<Student>(indexKeysDefinition, indexOptions);
    collection.Indexes.CreateOne(indexModel);
    

    thank for @NeilLunn .