MongoDB C# Driver Query Examples

In this post I would like to show a couple of useful examples on how to get started with MongoDB Driver in your C# code and .NET application.

Connecting to the database

First of all you need to create a MongoClient. Mongo client is a class handling the connection to your MongoDB server:

var mongoClient = new MongoClient("mongodb://db_user:password@localhost:27017/DatabaseName");

A note on the connection string. The DatabaseName in the connection string is the database against which you want to authenticate. You will provide the database name again when creating an instance of IMongoDatabase in the next step.

MongoClient can be a static instance or a singleton within your application, same as MongoDatabase which encapsulated access to a single database by its name:

var database = mongoClient.GetDatabase(DatabaseName);

Once you have the IMongoDatabase instance you can get reference to the collections. Even though the MongoDB allows storing objects of any schema into a single collection, it is a good idea to have a collection per each strongly types database entity. It means that a collection corresponds to a table in SQL database.

There is a generic method following this approach on the MongoDatabase object, returning a generic IMongoCollection<T> where T is your entity class. You retrieve collection like this:

var userCollection = database.GetCollection<Product>("Product");

Or better you can user the nameof(User) operator if you name the collections based on the class name:
var userCollection = database.GetCollection<Product>(nameof(Product));

You can have a factory method registered in your IoC/DI to inject the instances of IMongoCollection<> to your classes or just retrieve them from the static IMongoDatabase instance.

Entity class

The entity should contain the ID object, which in MongoDB by default is of type ObjectId. We can have a product class that looks like this in the C# code:

public class Product
{
[BsonElement("_id")]
public ObjectId Id { set; get; }
[BsonElement("_createddate")]
public DateTime CreateDate { set; get; }
public string Name { get; set; }
}

The attributes BsonElement are used to change the name of the fileds into which the properties are serialized in the database.

Basic commands

Once you have the connection to the database you might want to start with the basic CRUD operations. MongoDB C# driver provides a couple of approaches to query the database:

  • You can use lambda expression to filter the results.
  • The Mongo C# Driver query builder tools
  • IQueryable with Linq and extension methods

Select

To select a list of records based on a field filter you can use the following approaches:

var items = productCollection.Find(x => x.Name == "name").ToList();
var items2 = await productCollection.Find(x => x.Name == "name").ToListAsync();
var items3 = await productCollection.Find(Builders<Product>.Filter.Where(x => x.Name == "name")).ToListAsync();
var items4 = await productCollection.Find(Builders<Product>.Filter.Eq(x => x.Name , "name")).ToListAsync();
var items5 = productCollection.AsQueryable().Where(x => x.Name == "name").ToList();

As you see, you can use synchronous as well as async methods. You can convert the collection to an IQueryable object and use the standard Linq extension methods.

Update

There are again more ways how to update the records, but generally speaking the MongoDB Driver does not track changes to the entities and the best and most effective way is to update only the fields you want to:

venueCollection.UpdateMany(
Builders<Product>.Filter.Eq(x => x.Name, "name"),
Builders<Product>.Update.Set(x => x.Name, "New Name"));

When running the update you can again user the sync or async methods. In this example we first create a filter that identifies the records to be updated and then create the update command to update only the single propery – Name. The Update command returns the result which contains the number of update records.

Create and delete

Similar approach as for update is used for delete, based on the provided filter. Create is as simple as calling InsertOne or InserMany methods on the collection.

I will cover a more advanced update scenarios such as polymorphic data in the collections in my next post.

 

Send a Comment

Your email address will not be published.