MongoDB database is one of the most popular NoSql solutions on the market today. Of course, it provides support for .NET Core, as well as for other popular programming languages and frameworks.
In this article, I want to share my experience when I started to use Mongo as the main database with the .NET Core application. Before, I mainly used relational databases for a long time, and some NoSQL terms were confusing for me. Just like for many developers with a background in relational databases. You need to switch mindset - from relations and schema to no relations and schemaless.
No Entity Framework!?..
The default way to interact with SQL databases in .NET applications is Entity Framework. Although there are Entity Framework and EF Core providers for MongoDB as well, there is no reason to use them.
Using EF or any other ORM in the case of Mongo doesn’t bring you any benefits but creates an unnecessary level of abstraction.
When you design your domain model using standard API, you have more flexibility and take all advantages that give you a NoSQL engine.
So here is my first tip:
Use the official MongoDB .NET Driver -
mongodb.github.io/mongo-csharp-driver
This is the easiest way to interact with Mongo, and it comes with quite good documentation.
Connecting to MongoDB Database
To connect to MongoDB instance or instances, you will need to create an object of MongoClient class. This object will hold the pool of connections to the database. There is no need to dispose of it, as well as open and close connections.
The client itself is lightweight. Many instances of MongoClient will still share the same connections pool. However, the good practice is to have only one instance of MongoClient in the application. MongoClient is thread-safe.
Example of setting-up MongoDB client in ASP.NET Core as a singleton instance:
//Startup.cs
services.AddSingleton<IMongoClient>(new MongoClient("connection-string"));
Generally, there are several ways you can pass connection data.
The most common way and easiest one is to pass connection string in URI format:
new MongoClient("mongodb://localhost:27017");
- Connection String format is universal for all MongoDB drivers, so you can easily reuse the same connection string in other different applications or scripts;
- It is possible to set all needed options directly in Connection String, see
documentation;
- You can store the whole Connection String within credentials in secure storage, e.g. Key Vault;
If for some reason, you need to configure the connection in code, it is possible to instantiate MongoClient by passing MongoClientSettings, where you define all connection parameters.
My tips:
- Create only one MongoClient and share it across application;
- Instantiate MongoClient using URI connecting string if possible;
- The particular connection string should allow access to a single database ONLY. For security reasons and to avoid unwanted accidents;
Serialization and Mapping
In MongoDB, documents are stored in a specific JSON format called BSON (Binary JSON). What is BSON, and why is it used?.. In short, this format allows write/read operations on binary data on a disk in a more efficient way. Also, it will enable storing more complex data types.
Documents could be deserialized to BsonDocument class or POCO classes.
BsonDocument is a default “container” for any document. It represents documents using arrays. It is not very convenient to use, but it is flexible and can handle documents of any complexity. It somehow reminds me DataTable from ADO.NET.
Mapping is automatic. In most cases, you don’t need to do anything. If you need some customization, you can define special rules in code at app startup or decorate class properties with proper attributes.
Example POCO class of MongoDB document:
public class User: MongoEntity
{
public string Name{ get; set; }
public string Email{ get; set; }
[BsonDateTimeOptions(DateOnly = true)]
public DateTime DateOfBirth { get; set; }
}
public class MongoEntity
{
public ObjectId Id { get; set; }
public DateTime CreatedAt { get; set; }
}
My tips:
- Use base class for document classes, put there common for all document fields, e.g. Id;
- Try to stick with the default mapping
convention, use attributes if needed;
- If you need some not typical customization for all your documents create a custom
Convention rather than use attributes, in this way your documents classes stay cleaner;
Polymorphism
In contrast to
SQL databases in MongoDB, you can store documents with different schemas in the same collection.
To make it work, you need to tell Mongo which classes may appear in the document or field. To do this, use the RegisterClassMap method and put it at app startup. Also, you can use the [BsonKnownTypes] attribute.
For example, if I want to have a field in a document, let’s call it Payload, that stores different models depending on the field Category. For such polymorphic field, I need to use object in my entity class:
public class MyEntity
{
public string Category { get; set; }
public object Payload { get; set; }
}
Next, I need to register all classes which I plan to use for field Payload, for example, in the case of ASP.NET Core:
//Startup.cs
BsonClassMap.RegisterClassMap<MyVerySpecialClass>();
BsonClassMap.RegisterClassMap<MyVeryVerySpecialClass>();
Now I can save and store objects of registered classes into the Payload field, and Mongo will know how to deserialize it to the appropriate type.
What About IDs
Each MongoDB document must have an Id. In the BSON document, it is represented as the “_id” field, which acts as the primary key. By default, Mongo uses its own type for Id
ObjectId. However, it is possible to use other types. Driver by default support commonly used Id types: GUID, Object, String.
ObjectId is considered globally unique, and it allows to sort records ascending and descending. ObjectId consists of a timestamp value, a random value, an incrementing counter. Then you sort by ObjectId is roughly the same as sorting by creation time.
By convention, the driver will use a public member named `Id,` `id` or `_id.`
To specify a custom field, use [BsonId]
attribute:
[BsonId]
public Guid MyCustomId { get; set; }
If you don’t want to deal with ObjectId in your document classes, use [BsonRepresentation] attribute:
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
Here Id will be stored as ObjectId in the database with all its benefits. MongoDB driver will do serialization/deserialization for you. In code, it will be a standard string.
When a new document is added, Mongo will automatically generate a unique Id for the inserted document record.
My tips:
- In documents, classes keep Id as a string using BsonRepresentation attribute, in this way you avoid dependencies on MongoDB driver where it not needed, and deserialization problems in HTTP requests;
- If you create a big amount of documents at the same moment in the same process, ObjectId could be duplicated, if you have such cases, creating uniq index is a good idea;
Generic Repository
To make access to MongoDB collections easier and reduce code duplications, it makes sense to create a repository class and use it to interact with a database. You can tune and upgrade it to meet your needs. A repository should be initialized as a singleton.
With such a repository, we solve the following problems:
- Have a single point to access the database;
- No need to give the collection name; it happens automatically thanks to custom attributes;
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;
}
}
All document classes should be decorated with this attribute:
[AttributeUsage(AttributeTargets.Class, Inherited = false)]
public class MongoCollectionAttribute : System.Attribute
{
public MongoCollectionAttribute(string collectionName)
{
CollectionName = collectionName;
}
public string CollectionName { get; }
}
Usage is straightforward:
var document = await mongoDbRepository.GetCollection<MyDocument>()
.Find(c => c.Id == documentId)
.FirstOrDefaultAsync();
In Conclusion
MongoDB works excellent with .NET applications, and if you consider using MongoDB as a NoSQL solution in your .NET application, don’t hesitate to.
Please keep in mind that Mongo is not a substitute for relational databases. Each solution shines in its own field. So choose consciously depending on the problems you want to solve.
In this blog post, I intended to cover the getting started part of the very complex and vast subject of dealing with MongoDB in .NET core applications. That is why some very important topics, like querying and especially aggregating, which is quite tricky, are not covered. My next posts will try to dig deeper into nuances and more complex patterns, including Transactions and Read Isolation.
If you’re interested, follow nexocode and our
Zero Legacy article series to learn more from our engineering team.