Explore Developer Center's New Chatbot! MongoDB AI Chatbot can be accessed at the top of your navigation to answer all your MongoDB questions.

MongoDB Developer
C#
plus
Sign in to follow topics
MongoDB Developer Centerchevron-right
Developer Topicschevron-right
Languageschevron-right
C#chevron-right

Build Your First .NET Core Application with MongoDB Atlas

Nic Raboy6 min read • Published Jan 31, 2022 • Updated Jun 04, 2024
.NETC#
Facebook Icontwitter iconlinkedin icon
Rate this quickstart
star-empty
star-empty
star-empty
star-empty
star-empty
So you're a .NET Core developer or you're trying to become one and you'd like to get a database included into the mix. MongoDB is a great choice and is quite easy to get started with for your .NET Core projects.
In this tutorial, we're going to explore simple CRUD operations in a .NET Core application, something that will make you feel comfortable in no time!

The Requirements

To be successful with this tutorial, you'll need to have a few things ready to go.
  • .NET Core installed and configured.
  • MongoDB Atlas cluster, M0 or better, deployed and configured.
Both are out of the scope of this particular tutorial, but you can refer to this tutorial for more specific instructions around MongoDB Atlas deployments. You can validate that .NET Core is ready to go by executing the following command:
1dotnet new console --output MongoExample
We're going to be building a console application, but we'll explore API development in a later tutorial. The "MongoExample" project is what we'll use for the remainder of this tutorial.

Installing and Configuring the MongoDB Driver for .NET Core Development

When building C# applications, the common package manager to use is NuGet, something that is readily available in Visual Studio. If you're using Visual Studio, you can add the following:
1Install-Package MongoDB.Driver -Version 2.14.1
However, I'm on a Mac, use a variety of programming languages, and have chosen Visual Studio Code to be the IDE for me. There is no official NuGet extension for Visual Studio Code, but that doesn't mean we're stuck.
Execute the following from a CLI while within your project directory:
1dotnet add package MongoDB.Driver
The above command will add an entry to your project's "MongoExample.csproj" file and download the dependencies that we need. This is valuable whether you're using Visual Studio Code or not.
If you generated the .NET Core project with the CLI like I did, you'll have a "Program.cs" file to work with. Open it and add the following code:
1using MongoDB.Driver;
2using MongoDB.Bson;
3
4MongoClient client = new MongoClient("ATLAS_URI_HERE");
5
6List<string> databases = client.ListDatabaseNames().ToList();
7
8foreach(string database in databases) {
9 Console.WriteLine(database);
10}
The above code will connect to a MongoDB Atlas cluster and then print out the names of the databases that the particular user has access to. The printing of databases is optional, but it could be a good way to make sure everything is working correctly.
If you're wondering where to get your ATLAS_URI_HERE string, you can find it in your MongoDB Atlas dashboard and by clicking the connect button on your cluster.
MongoDB Atlas Connection String
MongoDB Atlas Connection String
The above image should help when looking for the Atlas URI.

Building a POCO Class for the MongoDB Document Model

When using .NET Core to work with MongoDB documents, you can make use of the BsonDocument class, but depending on what you're trying to do, it could complicate your .NET Core application. Instead, I like to work with classes that are directly mapped to document fields. This allows me to use the class naturally in C#, but know that everything will work out on its own for MongoDB documents.
Create a "playlist.cs" file within your project and include the following C# code:
1using MongoDB.Bson;
2
3public class Playlist {
4
5 public ObjectId _id { get; set; }
6 public string username { get; set; } = null!;
7 public List<string> items { get; set; } = null!;
8
9 public Playlist(string username, List<string> movieIds) {
10 this.username = username;
11 this.items = movieIds;
12 }
13
14}
In the above Playlist class, we have three fields. If you want each of those fields to map perfectly to a field in a MongoDB document, you don't have to do anything further. To be clear, the above class would map to a document that looks like the following:
1{
2 "_id": ObjectId("61d8bb5e2d5fe0c2b8a1007d"),
3 "username": "nraboy",
4 "items": [ "1234", "5678" ]
5}
However, if you wanted your C# class field to be different than the field it should map to in a MongoDB document, you'd have to make a slight change. The Playlist class would look something like this:
1using MongoDB.Bson;
2using MongoDB.Bson.Serialization.Attributes;
3
4public class Playlist {
5
6 public ObjectId _id { get; set; }
7
8 [BsonElement("username")]
9 public string user { get; set; } = null!;
10
11 public List<string> items { get; set; } = null!;
12
13 public Playlist(string username, List<string> movieIds) {
14 this.user = username;
15 this.items = movieIds;
16 }
17
18}
Notice the new import and the use of BsonElement to map a remote document field to a local .NET Core class field.
There are a lot of other things you can do in terms of document mapping, but they are out of the scope of this particular tutorial. If you're curious about other mapping techniques, check out the documentation on the subject.

Implementing Basic CRUD in .NET Core with MongoDB

Since we're able to connect to Atlas from our .NET Core application and we have some understanding of what our data model will look like for the rest of the example, we can now work towards creating, reading, updating, and deleting (CRUD) documents.
We'll start by creating some data. Within the project's "Program.cs" file, make it look like the following:
1using MongoDB.Driver;
2
3MongoClient client = new MongoClient("ATLAS_URI_HERE");
4
5var playlistCollection = client.GetDatabase("sample_mflix").GetCollection<Playlist>("playlist");
6
7List<string> movieList = new List<string>();
8movieList.Add("1234");
9
10playlistCollection.InsertOne(new Playlist("nraboy", movieList));
In the above example, we're connecting to MongoDB Atlas, getting a reference to our "playlist" collection while noting that it is related to our Playlist class, and then making use of the InsertOne function on the collection.
If you ran the above code, you should see a new document in your collection with matching information.
So let's read from that collection using our C# code:
1// Previous code here ...
2
3FilterDefinition<Playlist> filter = Builders<Playlist>.Filter.Eq("username", "nraboy");
4
5List<Playlist> results = playlistCollection.Find(filter).ToList();
6
7foreach(Playlist result in results) {
8 Console.WriteLine(string.Join(", ", result.items));
9}
In the above code, we are creating a new FilterDefinition filter to determine which data we want returned from our Find operation. In particular, our filter will give us all documents that have "nraboy" as the username field, which may be more than one because we never specified if the field should be unique.
Using the filter, we can do a Find on the collection and convert it to a List of our Playlist class. If you don't want to use a List, you can work with your data using a cursor. You can learn more about cursors in the documentation.
With a Find out of the way, let's move onto updating our documents within MongoDB.
We're going to add to our "Program.cs" file with the following code:
1// Previous code here ...
2
3FilterDefinition<Playlist> filter = Builders<Playlist>.Filter.Eq("username", "nraboy");
4
5// Previous code here ...
6
7UpdateDefinition<Playlist> update = Builders<Playlist>.Update.AddToSet<string>("items", "5678");
8
9playlistCollection.UpdateOne(filter, update);
10
11results = playlistCollection.Find(filter).ToList();
12
13foreach(Playlist result in results) {
14 Console.WriteLine(string.Join(", ", result.items));
15}
In the above code, we are creating two definitions, one being the FilterDefinition that we had created in the previous step. We're going to keep the same filter, but we're adding a definition of what should be updated when there was a match based on the filter.
To clear things up, we're going to match on all documents where "nraboy" is the username field. When matched, we want to add "5678" to the items array within our document. Using both definitions, we can use the UpdateOne method to make it happen.
There are more update operations than just the AddToSet function. It is worth checking out the documentation to see what you can accomplish.
This brings us to our final basic CRUD operation. We're going to delete the document that we've been working with.
Within the "Program.cs" file, add the following C# code:
1// Previous code here ...
2
3FilterDefinition<Playlist> filter = Builders<Playlist>.Filter.Eq("username", "nraboy");
4
5// Previous code here ...
6
7playlistCollection.DeleteOne(filter);
We're going to make use of the same filter we've been using, but this time in the DeleteOne function. While we could have more than one document returned from our filter, the DeleteOne function will only delete the first one. You can make use of the DeleteMany function if you want to delete all of them.
Need to see it all together? Check this out:
1using MongoDB.Driver;
2
3MongoClient client = new MongoClient("ATLAS_URI_HERE");
4
5var playlistCollection = client.GetDatabase("sample_mflix").GetCollection<Playlist>("playlist");
6
7List<string> movieList = new List<string>();
8movieList.Add("1234");
9
10playlistCollection.InsertOne(new Playlist("nraboy", movieList));
11
12FilterDefinition<Playlist> filter = Builders<Playlist>.Filter.Eq("username", "nraboy");
13
14List<Playlist> results = playlistCollection.Find(filter).ToList();
15
16foreach(Playlist result in results) {
17 Console.WriteLine(string.Join(", ", result.items));
18}
19
20UpdateDefinition<Playlist> update = Builders<Playlist>.Update.AddToSet<string>("items", "5678");
21
22playlistCollection.UpdateOne(filter, update);
23
24results = playlistCollection.Find(filter).ToList();
25
26foreach(Playlist result in results) {
27 Console.WriteLine(string.Join(", ", result.items));
28}
29
30playlistCollection.DeleteOne(filter);
The above code is everything that we did. If you swapped out the Atlas URI string with your own, it would create a document, read from it, update it, and then finally delete it.

Conclusion

You just saw how to quickly get up and running with MongoDB in your .NET Core application! While we only brushed upon the surface of what is possible in terms of MongoDB, it should put you on a better path for accomplishing your project needs.
If you're looking for more help, check out the MongoDB Community Forums and get involved.

Facebook Icontwitter iconlinkedin icon
Rate this quickstart
star-empty
star-empty
star-empty
star-empty
star-empty
Related
Tutorial

Adding MongoDB Atlas Vector Search to a .NET Blazor C# Application


Feb 29, 2024 | 10 min read
Tutorial

MongoDB Provider for EF Core Tutorial: Building an App with CRUD and Change Tracking


Jan 24, 2024 | 18 min read
Tutorial

Building an AI Agent With Semantic Kernel, C#, OpenAI, and MongoDB Atlas


Dec 02, 2024 | 13 min read
Tutorial

MongoDB C# Aggregation Pipeline Basics


Oct 11, 2024 | 5 min read
Table of Contents