EventGet 50% off your ticket to MongoDB.local NYC on May 2. Use code Web50!Learn more >>
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 Feb 03, 2023
.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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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

Working with MongoDB Transactions with C# and the .NET Framework


Sep 23, 2022 | 3 min read
Tutorial

Integrate Azure Key Vault with MongoDB Client-Side Field Level Encryption


May 24, 2022 | 9 min read
Tutorial

Build an Infinite Runner Game with Unity and the Realm Unity SDK


Feb 03, 2023 | 12 min read
Tutorial

Saving Data in Unity3D Using Files


Sep 07, 2022 | 11 min read
Table of Contents