Helpful Guidelines to Begin With MongoDB in .NET Core

Introduction to MongoDB and .NET Core

MongoDB is one of the leading NoSQL databases available today, known for its flexibility, scalability, and powerful querying capabilities. As a .NET Core developer, leveraging MongoDB can open up new opportunities to build robust and efficient applications without some of the restrictions imposed by traditional SQL databases.


In this comprehensive guide, we'll walk you through essential tips and practices for getting started with MongoDB in .NET Core, ensuring you can leverage its features effectively.


Why Choose MongoDB for .NET Core Applications?

When it comes to the tech stack for modern applications, the combination of MongoDB and .NET Core is a formidable one. Here are some reasons why developers choose this pairing:


  • NoSQL Flexibility: Unlike relational databases, MongoDB allows for flexible schema design, which is perfect for applications dealing with diverse data types.
  • Scalability: MongoDB scales horizontally, making it an ideal choice for applications expecting high traffic.
  • Document-Oriented Storage: MongoDB stores data in JSON-like documents known as BSON, which aligns well with modern application data structures.
  • Robust Ecosystem: With the official MongoDB .NET driver, integrating MongoDB into .NET Core applications is both seamless and well-documented.


Setting Up MongoDB in .NET Core

To start using MongoDB with .NET Core, you need to set up the right dependencies and configurations in your project. Here's a step-by-step guide:


Installing the MongoDB .NET Driver

The first step is to install the MongoDB .NET Driver, which provides a seamless interface for interacting with MongoDB from your .NET Core application. You can install this via NuGet Package Manager:


dotnet add package MongoDB.Driver --version x.x.x

Replace x.x.x with the latest version of the MongoDB.Driver.


Connecting to MongoDB

Connecting to a MongoDB instance in .NET Core involves creating a MongoClient object. This object will manage the connection pool to the MongoDB server. Here’s how you can set this up:


services.AddSingleton(new MongoClient("your-connection-string"));

Using Connection Strings

The most common way to connect to MongoDB is via a connection string in URI format, which looks something like this:


new MongoClient("mongodb://username:password@host:port/database");

Benefits of using URI format include:


  • Uniformity: Connection strings can be reused across different applications or scripts.
  • Flexibility: All necessary options can be set directly within the URI.
  • Security: Connection strings can be securely stored and managed, for instance, in Azure Key Vault.


Working with Data

MongoDB stores documents in a specific JSON format known as BSON (Binary JSON). Documents can be deserialized into BsonDocument or POCO (Plain Old CLR Object) classes. Here we explore both approaches.


Using POCO Classes

Using POCO classes is generally recommended since it aligns with object-oriented design principles commonly used in .NET applications. Here is an example POCO class:


public class User
{
public string Name { get; set; }
public string Email { get; set; }
[BsonDateTimeOptions(DateOnly = true)]
public DateTime DateOfBirth { get; set; }
public ObjectId Id { get; set; }
public DateTime CreatedAt { get; set; }
}

Attributes like BsonDateTimeOptions and BsonRepresentation allow for fine-tuning data serialization and deserialization.


Understanding Polymorphism in MongoDB

One of the powerful features of MongoDB is its ability to store documents with different schemas in the same collection. This is often referred to as polymorphism. To make this work, you need to inform MongoDB about the possible classes that might appear in the collection.


Registering Class Maps

Register class maps to handle polymorphic data structures. Here’s an example:


public class MyEntity
{
public string Category { get; set; }
public object Payload { get; set; }
}

BsonClassMap.RegisterClassMap<MySpecialClass>();
BsonClassMap.RegisterClassMap<AnotherSpecialClass>();

This allows the Payload field to store different types of objects, which MongoDB will correctly serialize and deserialize.


Handling IDs in MongoDB

Each MongoDB document must have an Id field, represented as "_id" in BSON. By default, MongoDB uses ObjectId type for IDs, but you can also customize this.


Using Custom ID Types

To use different ID types, you can use attributes like BsonId and BsonRepresentation. Here’s an example:


public class User
{
[BsonId]
public Guid CustomId { get; set; }
}

If you prefer using a simple type like string while still leveraging ObjectId benefits, use BsonRepresentation:


public class User
{
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
}

Setting Up a Generic Repository

To simplify interactions with MongoDB collections and reduce code duplication, consider implementing a generic repository class. This centralized access point improves code maintainability and readability.


Creating the Repository

Here's an example of a repository class:


public class MongoDbRepository
{
public IMongoDatabase Database { get; }

public MongoDbRepository(IMongoClient client, string dbName)
{
Database = client.GetDatabase(dbName);
}

public IMongoCollection<T> GetCollection<T>(ReadPreference readPreference = null) where T : class
{
return Database
.WithReadPreference(readPreference ?? ReadPreference.Primary)
.GetCollection<T>(GetCollectionName<T>());
}

public static string GetCollectionName<T>() where T : class
{
return (typeof(T).GetCustomAttributes(typeof(MongoCollectionAttribute), true).FirstOrDefault() as MongoCollectionAttribute)?.CollectionName;
}
}

To use this repository, document classes should be decorated with a custom attribute:


[AttributeUsage(AttributeTargets.Class, Inherited = false)]
public class MongoCollectionAttribute : System.Attribute
{
public MongoCollectionAttribute(string collectionName)
{
CollectionName = collectionName;
}

public string CollectionName { get; }
}

Usage example:


var document = await mongoDbRepository.GetCollection<MyDocument>()
.Find(c => c.Id == documentId)
.FirstOrDefaultAsync();

Conclusion

MongoDB is an excellent choice for .NET Core applications seeking a flexible and scalable NoSQL database solution. With the tips and best practices outlined in this guide, you’ll be well-equipped to integrate MongoDB into your .NET Core projects, leveraging its full potential.


Remember, while MongoDB offers many advantages, it’s essential to choose the right database solution based on your specific needs. Each database type, whether relational or NoSQL, excels in different aspects, and using the right tool for the task is crucial.


Stay tuned for more in-depth articles and advanced usage patterns, including transactions and complex querying capabilities. Follow us at our Zero Legacy article series to learn more from our engineering team. Feel free to sign up for our newsletter to get the latest updates straight to your inbox.