Useful Tips For Getting Started With MongoDB in .NET Core

Useful Tips For Getting Started With MongoDB in .NET Core

Witali Stinski - March 3, 2022

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");

What I like about Connection String in URI format:

  • 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.

About the author

Witali Stinski

Witali Stinski

Software Engineer

Linkedin profile Twitter

Vitali is a software developer with a passion for building scalable web applications, APIs, and backend solutions using Microsoft technologies such as Azure and .NET. Vitali has been consistently implementing best practices in coding to produce high-quality products that are always on time. He loves learning new technologies, diving deep into the details of any subject he’s unfamiliar with, and helping others learn as well.

Tempted to work
on something
as creative?

That’s all we do.

join nexocode

This article is a part of

Zero Legacy
36 articles

Zero Legacy

What goes on behind the scenes in our engineering team? How do we solve large-scale technical challenges? How do we ensure our applications run smoothly? How do we perform testing and strive for clean code?

Follow our article series to get insight into our developers' current work and learn from their experience. Expect to see technical details, architecture discussions, reviews on libraries and tools we use, best practices on software quality, and maybe even some fail stories.

check it out

More articles

Find us on

Need help with implementing AI in your business?

Let's talk blue circle

This site uses cookies for analytical purposes.

Accept Privacy Policy

In the interests of your safety and to implement the principle of lawful, reliable and transparent processing of your personal data when using our services, we developed this document called the Privacy Policy. This document regulates the processing and protection of Users’ personal data in connection with their use of the Website and has been prepared by Nexocode.

To ensure the protection of Users' personal data, Nexocode applies appropriate organizational and technical solutions to prevent privacy breaches. Nexocode implements measures to ensure security at the level which ensures compliance with applicable Polish and European laws such as:

  1. Regulation (EU) 2016/679 of the European Parliament and of the Council of 27 April 2016 on the protection of natural persons with regard to the processing of personal data and on the free movement of such data, and repealing Directive 95/46/EC (General Data Protection Regulation) (published in the Official Journal of the European Union L 119, p 1); Act of 10 May 2018 on personal data protection (published in the Journal of Laws of 2018, item 1000);
  2. Act of 18 July 2002 on providing services by electronic means;
  3. Telecommunications Law of 16 July 2004.

The Website is secured by the SSL protocol, which provides secure data transmission on the Internet.

1. Definitions

  1. User – a person that uses the Website, i.e. a natural person with full legal capacity, a legal person, or an organizational unit which is not a legal person to which specific provisions grant legal capacity.
  2. Nexocode – NEXOCODE sp. z o.o. with its registered office in Kraków, ul. Wadowicka 7, 30-347 Kraków, entered into the Register of Entrepreneurs of the National Court Register kept by the District Court for Kraków-Śródmieście in Kraków, 11th Commercial Department of the National Court Register, under the KRS number: 0000686992, NIP: 6762533324.
  3. Website – website run by Nexocode, at the URL: nexocode.com whose content is available to authorized persons.
  4. Cookies – small files saved by the server on the User's computer, which the server can read when when the website is accessed from the computer.
  5. SSL protocol – a special standard for transmitting data on the Internet which unlike ordinary methods of data transmission encrypts data transmission.
  6. System log – the information that the User's computer transmits to the server which may contain various data (e.g. the user’s IP number), allowing to determine the approximate location where the connection came from.
  7. IP address – individual number which is usually assigned to every computer connected to the Internet. The IP number can be permanently associated with the computer (static) or assigned to a given connection (dynamic).
  8. GDPR – Regulation 2016/679 of the European Parliament and of the Council of 27 April 2016 on the protection of individuals regarding the processing of personal data and onthe free transmission of such data, repealing Directive 95/46 / EC (General Data Protection Regulation).
  9. Personal data – information about an identified or identifiable natural person ("data subject"). An identifiable natural person is a person who can be directly or indirectly identified, in particular on the basis of identifiers such as name, identification number, location data, online identifiers or one or more specific factors determining the physical, physiological, genetic, mental, economic, cultural or social identity of a natural person.
  10. Processing – any operations performed on personal data, such as collecting, recording, storing, developing, modifying, sharing, and deleting, especially when performed in IT systems.

2. Cookies

The Website is secured by the SSL protocol, which provides secure data transmission on the Internet. The Website, in accordance with art. 173 of the Telecommunications Act of 16 July 2004 of the Republic of Poland, uses Cookies, i.e. data, in particular text files, stored on the User's end device.
Cookies are used to:

  1. improve user experience and facilitate navigation on the site;
  2. help to identify returning Users who access the website using the device on which Cookies were saved;
  3. creating statistics which help to understand how the Users use websites, which allows to improve their structure and content;
  4. adjusting the content of the Website pages to specific User’s preferences and optimizing the websites website experience to the each User's individual needs.

Cookies usually contain the name of the website from which they originate, their storage time on the end device and a unique number. On our Website, we use the following types of Cookies:

  • "Session" – cookie files stored on the User's end device until the Uses logs out, leaves the website or turns off the web browser;
  • "Persistent" – cookie files stored on the User's end device for the time specified in the Cookie file parameters or until they are deleted by the User;
  • "Performance" – cookies used specifically for gathering data on how visitors use a website to measure the performance of a website;
  • "Strictly necessary" – essential for browsing the website and using its features, such as accessing secure areas of the site;
  • "Functional" – cookies enabling remembering the settings selected by the User and personalizing the User interface;
  • "First-party" – cookies stored by the Website;
  • "Third-party" – cookies derived from a website other than the Website;
  • "Facebook cookies" – You should read Facebook cookies policy: https://www.facebook.com/policy/cookies
  • "Other Google cookies" – Refer to Google cookie policy: www.google.com/policies/technologies/types/

3. How System Logs work on the Website

User's activity on the Website, including the User’s Personal Data, is recorded in System Logs. The information collected in the Logs is processed primarily for purposes related to the provision of services, i.e. for the purposes of:

  • analytics – to improve the quality of services provided by us as part of the Website and adapt its functionalities to the needs of the Users. The legal basis for processing in this case is the legitimate interest of Nexocode consisting in analyzing Users' activities and their preferences;
  • fraud detection, identification and countering threats to stability and correct operation of the Website.

4. Cookie mechanism on the Website

Our site uses basic cookies that facilitate the use of its resources. Cookies contain useful information and are stored on the User's computer – our server can read them when connecting to this computer again. Most web browsers allow cookies to be stored on the User's end device by default. Each User can change their Cookie settings in the web browser settings menu: Google ChromeOpen the menu (click the three-dot icon in the upper right corner), Settings > Advanced. In the "Privacy and security" section, click the Content Settings button. In the "Cookies and site date" section you can change the following Cookie settings:

  • Deleting cookies,
  • Blocking cookies by default,
  • Default permission for cookies,
  • Saving Cookies and website data by default and clearing them when the browser is closed,
  • Specifying exceptions for Cookies for specific websites or domains

Internet Explorer 6.0 and 7.0
From the browser menu (upper right corner): Tools > Internet Options > Privacy, click the Sites button. Use the slider to set the desired level, confirm the change with the OK button.

Mozilla Firefox
browser menu: Tools > Options > Privacy and security. Activate the “Custom” field. From there, you can check a relevant field to decide whether or not to accept cookies.

Opera
Open the browser’s settings menu: Go to the Advanced section > Site Settings > Cookies and site data. From there, adjust the setting: Allow sites to save and read cookie data

Safari
In the Safari drop-down menu, select Preferences and click the Security icon.From there, select the desired security level in the "Accept cookies" area.

Disabling Cookies in your browser does not deprive you of access to the resources of the Website. Web browsers, by default, allow storing Cookies on the User's end device. Website Users can freely adjust cookie settings. The web browser allows you to delete cookies. It is also possible to automatically block cookies. Detailed information on this subject is provided in the help or documentation of the specific web browser used by the User. The User can decide not to receive Cookies by changing browser settings. However, disabling Cookies necessary for authentication, security or remembering User preferences may impact user experience, or even make the Website unusable.

5. Additional information

External links may be placed on the Website enabling Users to directly reach other website. Also, while using the Website, cookies may also be placed on the User’s device from other entities, in particular from third parties such as Google, in order to enable the use the functionalities of the Website integrated with these third parties. Each of such providers sets out the rules for the use of cookies in their privacy policy, so for security reasons we recommend that you read the privacy policy document before using these pages. We reserve the right to change this privacy policy at any time by publishing an updated version on our Website. After making the change, the privacy policy will be published on the page with a new date. For more information on the conditions of providing services, in particular the rules of using the Website, contracting, as well as the conditions of accessing content and using the Website, please refer to the the Website’s Terms and Conditions.

Nexocode Team

[Zero Legacy]

Want to be a part of our engineering team?

Join our teal organization and work on challenging projects.

CHECK OPEN POSITIONS