Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a mongodb capped collection using c# api

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#?

like image 447
Ben Avatar asked Jul 03 '12 18:07

Ben


3 Answers

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,
    });
}
like image 169
i3arnon Avatar answered Sep 18 '22 17:09

i3arnon


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);
like image 35
JefClaes Avatar answered Sep 18 '22 17:09

JefClaes


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.

like image 28
Nikola Anusev Avatar answered Sep 19 '22 17:09

Nikola Anusev