osman Rahimi
osman Rahimi

Reputation: 1497

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

Upvotes: 4

Views: 6782

Answers (2)

Dharmeshsharma
Dharmeshsharma

Reputation: 691

For Updated version 2.8 and above to help more people.

var keys = Builders<ResponseCache>.IndexKeys.Ascending("expireAt");
var model = new CreateIndexModel<ResponseCache>(keys, new CreateIndexOptions() { ExpireAfter = new TimeSpan(0, 15, 0) });
try
{
    _repository.Indexes.CreateOne(model);
}
catch (Exception ex)
{
}

_repository.InsertOne(responseCache);

Create Index with TTL 15 Min. it is perfectly working fine for me.

Thanks

Upvotes: 4

osman Rahimi
osman Rahimi

Reputation: 1497

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 .

Upvotes: 6

Related Questions