简体   繁体   English

如何使用 TTL 创建 MongoDB 集合?

[英]How to create MongoDB collection with TTL?

I create a collection of objects我创建了一个对象集合

public class User
{
public User(string fullname, string email)
{
Fullname = fullname;
Email = email;
}

    public string Fullname { get; }
    public string Email { get; }
}

And create the index and some docs并创建索引和一些文档

var collection = _database.GetCollection(“bar”);
collection.Indexes.CreateOne(new CreateIndexModel
(new BsonDocument(“lastModifiedDate”, 1), new CreateIndexOptions { ExpireAfter = new TimeSpan(0, 0, 30) }));

            var user = new User("Vasya", "billgates@ms.com");
            collection.InsertOne(user.ToBsonDocument());
            var user1 = new User("Petya", "Petya@ms.com");
            collection.InsertOne(user1.ToBsonDocument());
            var user2 = new User("Kolya", "Kolya@ms.com");
            collection.InsertOne(user2.ToBsonDocument());
            count = collection.CountDocuments(new BsonDocument());

But when I see http://localhost:8081/db/dbtest/ then I do not see any TTL and documents do not expire after 30 secs.但是当我看到 http://localhost:8081/db/dbtest/ 然后我看不到任何 TTL 并且文档在 30 秒后不会过期。

What I do wrong?我做错了什么? How to create collection or documents in it with TTL?如何使用 TTL 在其中创建集合或文档?

Your user object doesn't have the field you specified on the index您的用户 object 没有您在索引中指定的字段

public class User
{
    public User(string fullname, string email, DateTime lastModifiedDate) 
    {
        Fullname = fullname;
        Email = email;
        LastModifiedDate = lastModifiedDate;
    }

    public string Fullname { get; }
    public string Email { get; }
    public DateTime LastModifiedDate { get; }
}

Also, the default convention for serialization in MongoDB C# Driver is not camel case so you'll need to update your index to the following:此外,MongoDB C# 驱动程序中序列化的默认约定不是骆驼大小写,因此您需要将索引更新为以下内容:

var collection = _database.GetCollection("bar");
collection.Indexes.CreateOne(new CreateIndexModel
(new BsonDocument("LastModifiedDate", 1), new CreateIndexOptions { ExpireAfter = new TimeSpan(0, 0, 30) }));

You might also want to embrace the type safety that C# and the MongoDB Driver gives you by using your User type instead of the BsonDocument.您可能还希望通过使用用户类型而不是 BsonDocument 来接受 C# 和 MongoDB 驱动程序为您提供的类型安全。 Below is an example of how to do this.以下是如何执行此操作的示例。

using MongoDB.Driver;

var client = new MongoClient();
var database = client.GetDatabase("test");
var collection = database.GetCollection<User>("users");
await collection.Indexes.CreateOneAsync(
    Builders<User>.IndexKeys.Ascending(x => x.LastModifiedDate),
    new CreateIndexOptions { ExpireAfter = new TimeSpan(0, 0, 30) });

var user = new User("Vasya", "billgates@ms.com", DateTime.UtcNow);
collection.InsertOne(user);
var user1 = new User("Petya", "Petya@ms.com", DateTime.UtcNow);
collection.InsertOne(user1);
var user2 = new User("Kolya", "Kolya@ms.com", DateTime.UtcNow);
collection.InsertOne(user2);

for (var i = 0; i < 10; i++)
{
    var count = await collection.CountDocumentsAsync(Builders<User>.Filter.Empty);
    Console.WriteLine($"Count: {count} @ {DateTime.UtcNow}");
    await Task.Delay(10000);
}


// Count: 4 @ 02/01/2022 11:42:13
// Count: 4 @ 02/01/2022 11:42:23
// Count: 4 @ 02/01/2022 11:42:33
// Count: 4 @ 02/01/2022 11:42:43
// Count: 4 @ 02/01/2022 11:42:53
// Count: 1 @ 02/01/2022 11:43:03
// Count: 1 @ 02/01/2022 11:43:13
// Count: 1 @ 02/01/2022 11:43:23
// Count: 1 @ 02/01/2022 11:43:33
// Count: 0 @ 02/01/2022 11:43:43


public class User
{
    public User(string fullname, string email, DateTime lastModifiedDate)
    {
        Fullname = fullname;
        Email = email;
        LastModifiedDate = lastModifiedDate;
    }

    public string Fullname { get; }
    public string Email { get; }
    public DateTime LastModifiedDate { get; }
}

You might notice that the documents don't get deleted at once but as said in the MongoDB docs您可能会注意到文档不会立即被删除,但正如 MongoDB 文档中所述

The background task that removes expired documents runs every 60 seconds.删除过期文档的后台任务每 60 秒运行一次。 As a result, documents may remain in a collection during the period between the expiration of the document and the running of the background task.因此,在文档到期和后台任务运行之间的时间段内,文档可能会保留在集合中。 https://docs.mongodb.com/manual/core/index-ttl/#timing-of-the-delete-operation https://docs.mongodb.com/manual/core/index-ttl/#timing-of-the-delete-operation

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM