Search code examples
c#mongodbazure-cosmosdbttlmongodb.driver

Setting time to live (TTL) in Azure DocumentDB using MongoDB.Driver 2


I'm trying to implement TTL in DocumentDB by using MongoDB.Driver. I created an index like

await collection.Indexes.CreateOneAsync
(
    Builders<T>.IndexKeys.Ascending("_id123"),
    new CreateIndexOptions { ExpireAfter = new TimeSpan(0, 0, 10) }
);

The above code is creating the _id123 index without any errors, but the inserted data is not expiring after 10sec. Please help me to resolve this.


Solution

  • Based on my experience, please have a try to use the _ts field. We can get more information from the document. I do a demo for creating TTL index on my side, it works correctly. The following is the detail steps.

    1.Create C# console project and add MongoDB SDK

    2.Add a Person Class

    using MongoDB.Bson;
    public class Person
            {
                public ObjectId Id { get; set; }
                public string Name { get; set; }
            }
    

    3.Create MongodB client and we can get the code from Azure portal.

    enter image description here

    4.Add document to collection

     var db = mongoClient.GetDatabase("dbname");
    
     var collection = db.GetCollection<Person>("collectionname");
    
     collection.InsertOne(new Person() {Name = "tom"});
    

    5.Check from the Azure portal

    enter image description here

    6.Create TTL index on _ts field

     var indexs = collection.Indexes.CreateOneAsync(Builders<Person>.IndexKeys.Ascending("_ts"),
     new CreateIndexOptions { ExpireAfter = new TimeSpan(0, 0, 10) }).Result;
    

    enter image description here

    Package.config file

    <?xml version="1.0" encoding="utf-8"?>
    <packages>
      <package id="MongoDB.Bson" version="2.4.3" targetFramework="net451" />
      <package id="MongoDB.Driver" version="2.4.3" targetFramework="net451" />
      <package id="MongoDB.Driver.Core" version="2.4.3" targetFramework="net451" />
      <package id="System.Runtime.InteropServices.RuntimeInformation" version="4.3.0" targetFramework="net451" />
    </packages>