How to use MongoDB Atlas with .NET/.NET Core

MongoDB is a flexible, general-purpose document database that is ideally suited for modern applications. Microsoft’s .NET Frameworks and languages such as C# are equally popular and versatile. Developers can use these two pieces of technology, along with MongoDB Atlas, a fully managed, multi-cloud database service, to rapidly create powerful applications.

Table of Contents

  1. Introduction to MongoDB and .NET/.NET Core
  2. The difference between .NET Framework and .NET Core/.NET 5
  3. Installation Prerequisite
  4. Adding the .NET Driver
  5. Connecting to MongoDB Atlas
  6. How to use MongoDB with .NET
    • Creating Collections/Documents
    • Reading Data
    • Updating Data
    • Deleting Data

Introduction to MongoDB and .NET/.NET Core

With its versatility, easy-to-read syntax and vast breadth of learning resources, C# has quickly become a favorite tool for web and mobile apps, game development and business applications. In fact, the Stack Overflow Developer Survey 2020 had C# as one of the top 10 most popular languages, -- while MongoDB has been ranked the most wanted database by the same survey 4 years in a row.

In both cases, their general-purpose nature, combined with the power of the cloud, makes them compatible with lots of different types of projects. MongoDB’s native C#/.NET driver allows developers to take advantage of MongoDB’s powerful document databases from their C# applications.

Differences between .NET Core/.NET 5 and .NET Framework

.NET Core is an evolution of the .NET framework, optimized for cross-platform use and designed to be fully open-source. Microsoft is currently working to integrate a lot of its frameworks and libraries into one product and under one SDK called .NET 5.0.

Here are some key differences between .NET and .NET core.

.NET Framework.NET Core
* Long-term support of a legacy .NET implementation* Optimized for full-stack, cross-platform functionality
* Designed with MSFT Windows in mind* Designed for both on the web and desktop (Windows, Linux and Mac)
* Based on legacy .NET concepts* Based on the successor of the .NET Framework.
* Not open-source and not designed for containerized environments* Open source and designed to work with containerized environments.

Prerequisite

Before you begin, you'll need to ensure you've completed a few preparatory steps.

  1. If you haven't already, install .NET Core 3.1 or above and install your preferred IDE (Visual Studio or VS Code) .
  2. Create a MongoDB database. The easiest way to get started with MongoDB is to create a free cluster in MongoDB Atlas, MongoDB's fully-managed, multi-cloud document database service.

Follow Along with Atlas

Launch a new cluster or migrate to MongoDB Atlas with zero downtime.

Adding the MongoDB Driver

In the following sections, you are going to learn how to start using the MongoDB Driver and implement the basic Create, Read, Update, Delete (CRUD) functions.

Let’s create a game listing application using the ASP.NET Core Web API. Here's the GitHub repo for "GamesServices", which lists games as well as their price and the category they belong to.

The MongoDB Driver for C#/.NET is very easy to install using Microsoft’s Nuget Package manager in your development environment, or using the .NET SDK available in your Command Line Interface (CLI).

CLI

One way of adding the MongoDB driver to your application is via the CLI. When you install .NET Core/.NET 5.0 on your machine, you get the .NET SDK command line tools out of the box.

Run the following command from the root directory of the project, inside your CLI of choice:

dotnet add package MongoDB.Driver

You can also add the driver via Nuget Package Manager within Visual Studio, or by editing your .csproj file to add the MongoDB.Driver reference to the ItemGroup. Your .csproj file will then look very similar to below:

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net5.0</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="MongoDB.Driver" Version="2.12.4" />
  </ItemGroup>
</Project>

Connect to MongoDB Atlas

The most straightforward way is to initiate a MongoClient instance with the Atlas connection string URI taken from your clusters connect tab.

The MongoClient is a class available from the MongoDB.Driver package, and you need an instance of it in your code to allow you to connect and access your cluster.

In order to use the MongoDB client in your code, ensure you have the correct using statements at the top of your service class, as shown in GamesServices.cs.

Getting your connection string

In order to create the client, you will need to pass the connection string to access your database.

The connection string can be found in the Atlas UI. The following steps will show you how to get your connection string:

  1. Visit the Atlas UI and ensure you are logged into your account
  2. Ensure you are on the Clusters page. It should be the default page but if not, select it from the left-hand menu on the page.

mongodb .net screenshot

  1. Click the ‘Connect’ button for the Cluster you created earlier.

mongodb .net screenshot

  1. Select ‘Connect your application’

mongodb .net screenshot

  1. Copy the provided connection string into the create code, substituting any values within < > such as <password> with your details.

mongodb .net screenshot

In production we recommend placing the string and passwords in a secure source not exposed as a clear text code. A commonly used secure source for information in .NET applications is user secrets.

Once you have your connection string, you can create an instance of the client and pass it in as per below, replacing the template string below with your connection string :

var client = new MongoClient("mongodb+srv://<username>:<password>@<atlas-cluster>.mongodb.net/myFirstDatabase?retryWrites=true&w=majority");

In our sample application, the client is created inside a GamesService class. This service was created to give us access to all the CRUD operations.

How to use MongoDB with .NET

Now that we have a client, it is time to connect to the database using this client and begin to add in the CRUD functionality.

In the sample repo, all the following code is placed in the GamesService class.

Accessing a Database

var database = client.GetDatabase("GamesDB");

Creating a Collection and MongoDB Documents

In MongoDB, information is stored in BSON Documents. BSON is a binary, JSON-like structure. It supports the same data types as JSON with a few extras such as date, raw binary as well as more number types such as integer, long and float.

A collection is what MongoDB calls a group of documents in one ‘container’.

As part of the MongoDB.Driver, we have access to an interface, allowing us to choose the type of collection . In the sample application, this is a Game type, which is a class we defined with the same properties as the field in our document.

Use the InsertOne method to create a single document inside a collection. If a collection does not exist, the first write operation will implicitly create it. Same happens when we create a database, the first structure inside a database will implicitly create it.

var games = database.GetCollection<Game>("Games"); 
Game newGame = new Game() 
{
  Name = "Monopoly",
  Price = 22, 
  Category = "Board Game" 
 }; 
 
// Inserting the first document will create collection named "Games"
games.InsertOne(newGame);

Use InsertMany or BulkWrite to insert multiple documents at once. For more please read our writing reference.

Read Documents

Use the Find or Aggregate method to read documents. You may want to find all documents in the collection to return them as a list:

public List<Game> Get() => _games.Find(game => true).ToList();

Here, we are passing a filter expression which is the game we want to find. The boolean true is there because we don’t need to carry out any filtering and just want all games in our collection.

You can also find a single document based on id:

public Game Get(string id) => _games.Find(game => game.Id == id).FirstOrDefault();

For more information read our reading reference.

Updating Documents

Updating documents is done via the UpdateOne or UpdateMany methods. As well as these, there is the option to run ReplaceOne to replace a full document. With the object-oriented nature of C#, the simplest way to update a document is to pass it the id to update and the updated object model of the document, in our case Game, to the ReplaceOne method:

public void Update(string id, Game updatedGame) => _games.ReplaceOne(game => game.Id == id, updatedGame);

Deleting Documents

The MongoDB.Driver also makes it very simple to delete documents. The following code takes an id and deletes a document with the matching id:

public void Delete(string id) => _games.DeleteOne(game => game.Id == id);

Testing the Web API

The sample application is a Web API project which means that while running, you can actually use your favourite API client, such as Postman, to carry out all the CRUD operations by calling those endpoints, found in the GamesController class. These call into the GamesService where we added in the code that uses the MongoDB.Driver package to work with the database. Let’s have a look at how you would call these endpoints with values.

Create

Make a POST request to localhost:<port>/api/games, passing it a JSON object in the body which defines the fields for the new game.

mongodb .net screenshot- create

mongodb .net screenshot- create

Read

Make a GET request to localhost:/api/games:

mongodb .net screenshot- read

mongodb .net screenshot- read

Update

Make a PUT request to localhost:<port>/api/games, passing the id of the document you want to update as a query parameter, as well as a JSON object in the body with the values and updates you want to be applied.

mongodb .net screenshot- update

mongodb .net screenshot- update

mongodb .net screenshot- update

Delete

Make a DELETE request to localhost:<port>/api/games/{id} to delete the document.

mongodb .net screenshot- delete

mongodb .net screenshot- delete

Using Realm .NET SDK with MongoDB Atlas

MongoDB Realm is a mobile database and a Cloud backend-as a-service platform. It has a Realm .NET SDK allowing a seamless integration for .NET and Xamarin applications. The local Realm database can use the offline-first sync to MongoDB Atlas.

This allows developers to build cross-platform applications without the need of spinning backend servers and managing their connection pools and database credentials.

The Realm .NET SDK offers a simpler integration to the Unity 3D framework to build gaming applications.

FAQs

How do I connect MongoDB with ASP.NET?

Connecting ASP.NET Core applications to MongoDB is done via the .NET driver or the Realm .NET SDK, depending on your use case and stack.

How do I work with MongoDB from a .NET application?

You can use the .NET driver or Realm SDK to allow your application to connect and interact with data stored in MongoDB. Realm allows you to take advantage of the power of a mobile database and the Realm cloud platform, including offline-first sync.

The drivers and sdk provide all the CRUD (Create, Read, Update and Delete) operations MongoDB has to offer.

Want to learn more about using MongoDB with .NET?

Check out the following resources: