使用c#api创建mongodb上限集合
使用C#MongoDB驱动程序,我们目前创建我们的集合,如下所示:
MongoServer mongoServer = MongoServer.Create("some conn str"); MongoDatabase db = mongoServer.GetDatabase("mydb"); MongoCollection logs = db.GetCollection("mycoll");
我想使用mycoll
作为上限集合。 我没有看到任何关于如何使用C#驱动程序创建上限集合的示例或文档细节。 我发现了大量的JS示例,甚至是一个Java示例(这里: 在java中创建一个mongodb上限集合 )。
有没有人必须这样做,或者知道它是否可能在C#中?
创建集合时,需要使用CollectionOptions
指定集合的上限:
CollectionOptionsBuilder options = CollectionOptions.SetCapped(true); database.CreateCollection("mycoll", options);
您需要显式创建集合(通过调用CreateCollection
方法)才能提供您的选项。 使用不存在的集合调用GetCollection
时,将使用默认选项隐式创建它。
这是另一个例子; 不要忘记设置MaxSize和MaxDocuments属性。
var server = MongoServer.Create("mongodb://localhost/"); var db = server.GetDatabase("PlayGround"); var options = CollectionOptions .SetCapped(true) .SetMaxSize(5000) .SetMaxDocuments(100); if (!db.CollectionExists("Log")) db.CreateCollection("Log", options);
从驱动程序的v2.0开始,有一个新的async
-only API。 不应再使用旧的API,因为它是新API的阻止外观,不推荐使用。
目前推荐的创建上限集合的方法是使用CreateCollectionOptions
实例调用和等待IMongoDatabase.CreateCollectionAsync
,该实例指定Capped = true
和MaxSize =
或MaxDocuments =
(或两者)。
async Task CreateCappedCollectionAsync() { var database = new MongoClient().GetDatabase("HamsterSchool"); await database.CreateCollectionAsync("Hamsters", new CreateCollectionOptions { Capped = true, MaxSize = 1024, MaxDocuments = 10, }); }