Search code examples
c#.netmongodbmongodb-.net-driver

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


Solution

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