Creating a mongodb capped collection using c# api

13,901

Solution 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.

Solution 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,
    });
}

Solution 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);
Share:
13,901
Ben
Author by

Ben

Updated on July 26, 2022

Comments

  • Ben
    Ben almost 2 years

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