Collections

Get a collection reference

In order to read/write data from/to a database collection, first you need to get a reference to that collection. The collection doesn't have to exist already and if it doesn't, it will be created automatically the very first time you run a read or write operation. Use the GetCollection<T> method on an IMongoDatabase reference to get a collection reference.

IMongoDatabase.GetCollection<T>(string collection)
AccessCollections.cs
// Get a reference to the database
var database = Client
    .GetDatabase(Constants.SamplesDatabase);

// Get a reference to a database's collection named 'users'
var personsTypedCollection = database
    .GetCollection<User>(Constants.UsersCollection);

Notice that in the above sample the collection reference is a typed collection of type IMongoCollection<User> and most of its methods require parameters of type User. It basically implies that a document stored in the collection will match and can be deserialized by the driver back to a User entity.

This is different than getting a reference collection of type IMongoCollection<BsonDocument>:

var bsonPersonsCollection = database
    .GetCollection<BsonDocument>(Constants.UsersCollection);

With a IMongoCollection<BsonDocument>collection reference, you can build pretty much all MongoDB queries you write in the shell, even the complex ones. The downside though is that you end up writing ugly code that is hard to maintain when models change. Luckily, these docs' goal is to learn you how to build typed MongoDB queries

Create collections

You can create a collection using the CreateCollection method on a IMongoDatabase reference.

IMongoDatabase.CreateCollection(string collection)
AccessCollections.cs
var loginsCollectionName = "logins";
await database
    .CreateCollectionAsync(loginsCollectionName);

Capped collection

A Capped collection in MongoDB is a special fixed-size collection where when its allocated sized is filled, the oldest documents inserted are automatically removed to make room for the new ones. You can define a collection as capped only during its creation by using the CreateCollectionOptions and setting the values for either (or both) the max documents and the max size. If any max documents or max size exceeds, the latest document will be removed to make room for the next one inserted.

Remember that in case you set the MaxDocuments you are required to set the MaxSize as well

AccessCollections.cs
await database
    .CreateCollectionAsync(Constants.TravelersCollection,
        new CreateCollectionOptions()
        {
            Capped = true, MaxDocuments = 3, MaxSize = 10000
        });
        var travelers = RandomData.GenerateTravelers(3);

Why a capped collection anyway?

  • Order retrieved is always same as the order inserted. This is not guaranteed with a normal collection

  • Automatic clear up ensures fixed collection size and hence efficient to work with

  • Ideal for scenarios where you want high insertion throughput while you don't care or want to get rid of old data

Reference

List collections

You can get all available collections in a database by using the ListCollections method on an IMongoDatabase reference.

IMongoDatabase.ListCollections()
AccessCollections.cs
var database = Client.GetDatabase(Constants.SamplesDatabase);

// Get all collections
var collections = (await database
    .ListCollectionsAsync()).ToList();

Drop collections

Delete a collection using the DropCollection method. The collection along with its data will be entirely removed.

IMongoDatabase.DropCollection(string collection)
var loginsCollectionName = "logins";
await database
    .DropCollectionAsync(loginsCollectionName);

Last updated