Create & Read Operations

This lesson teaches how to create the class used to access MongoDB and the methods to perform the basic CRUD operations is C#.

Users Repository

The goal of this lesson is to create a class which will give us the ability to do simple CRUD operations on the users collection.

The first thing we need to do is connect to the database from our application. The easiest way to do this is by using the MongoClient class, available via the MongoDB driver that has already been installed for you. (its constructor requires a connection string, which we will provide).

Alternatively, MongoClientSettings class, available via the MongoDB driver, can be used as it provides various possibilities. One such possibility is the ClusterConfiguration property, which is of the ClusterBuilder type and used for configuring clusters.

Other classes that we need to use are MongoDatabase, to access defined databases (blog in this case), and MongoCollection, to access defined collections (users in this case).

Here is how it looks in code:

Get hands-on with 1200+ tech skills courses.