设置 TTL 在 Mongodb c# 中不起作用 [英] Set TTL doesnt work in Mongodb c#
问题描述
我在 c# 中使用 MongoDb.我插入一个像下面这样的学生
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);
我想设置一个 TTL
以在几秒钟后删除数据,我尝试这样做:
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; }
}
注意:我对 DateTime
有问题,db 中存储的数据与 Visual Studio
中的 Set Date 不同
Note : and I have problem with DateTime
, stored data in db is different with Set Date in Visual Studio
推荐答案
再次阅读 Mongodb 文档后,我的代码有错误添加了 Index
.TTL
有一些限制.
After reading Mongodb documents again , there was a mistake in my code to add Index
. there some restriction to work TTL
.
如果文档中的索引字段不是日期或保存日期值的数组,则文档不会过期.
我尝试在 Name
上设置索引,但它不包含 Date
.
I'v tried to set Index on Name
and it does not contain Date
.
下面的代码工作正常.
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);
感谢 @NeilLunn.
这篇关于设置 TTL 在 Mongodb c# 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!