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.
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>
:
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.
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
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
List collections
You can get all available collections in a database by using the ListCollections
method on an IMongoDatabase
reference.
Drop collections
Delete a collection using the DropCollection
method. The collection along with its data will be entirely removed.
Last updated