Creating a mongodb capped collection using c# api

 ̄綄美尐妖づ 提交于 2019-12-06 23:25:05

问题


Using the C# MongoDB driver, we currently create our collection like so:

MongoServer mongoServer = MongoServer.Create("some conn str");
MongoDatabase db = mongoServer.GetDatabase("mydb");
MongoCollection logs = db.GetCollection("mycoll");

I would like to use mycoll as a capped collection. I haven't seen any examples or documentation specifics on how to create a capped collection using the C# driver. I've found tons of JS examples, and even a Java example (here: Creating a mongodb capped collection in java).

Has anyone had to do this before, or know if it's possible in C#?


回答1:


When creating a collection, you need to specify that the collection should be capped by using CollectionOptions:

CollectionOptionsBuilder options = CollectionOptions.SetCapped(true);
database.CreateCollection("mycoll", options); 

You need to create the collection explicitly (by calling CreateCollection method) to be able to provide your options. When calling GetCollection with non-existing collection, it gets implicitly created with default options.




回答2:


Starting from v2.0 of the driver there's a new async-only API. The old API should no longer be used as it's a blocking facade over the new API and is deprecated.

The currently recommended way to create a capped collection is by calling and awaiting IMongoDatabase.CreateCollectionAsync with a CreateCollectionOptions instance that specifies Capped = true and MaxSize = <cap size in bytes> or MaxDocuments = <cap in doc count> (or both).

async Task CreateCappedCollectionAsync()
{
    var database = new MongoClient().GetDatabase("HamsterSchool");
    await database.CreateCollectionAsync("Hamsters", new CreateCollectionOptions
    {
        Capped = true,
        MaxSize = 1024,
        MaxDocuments = 10,
    });
}



回答3:


Here is another example; don't forget to set the MaxSize and MaxDocuments property.

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);


来源:https://stackoverflow.com/questions/11317070/creating-a-mongodb-capped-collection-using-c-sharp-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!