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!
To be successful with this tutorial, you’ll need to have a few things ready to go.
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:
dotnet 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.
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:
Install-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:
dotnet 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:
using MongoDB.Driver;
using MongoDB.Bson;
MongoClient client = new MongoClient("ATLAS_URI_HERE");
List<string> databases = client.ListDatabaseNames().ToList();
foreach(string database in databases) {
Console.WriteLine(database);
}
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.
The above image should help when looking for the Atlas URI.
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:
using MongoDB.Bson;
public class Playlist {
public ObjectId _id { get; set; }
public string username { get; set; } = null!;
public List<string> items { get; set; } = null!;
public Playlist(string username, List<string> movieIds) {
this.username = username;
this.items = movieIds;
}
}
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:
{
"_id": ObjectId("61d8bb5e2d5fe0c2b8a1007d"),
"username": "nraboy",
"items": [ "1234", "5678" ]
}
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:
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
public class Playlist {
public ObjectId _id { get; set; }
[BsonElement("username")]
public string user { get; set; } = null!;
public List<string> items { get; set; } = null!;
public Playlist(string username, List<string> movieIds) {
this.user = username;
this.items = movieIds;
}
}
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.
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:
using MongoDB.Driver;
MongoClient client = new MongoClient("ATLAS_URI_HERE");
var playlistCollection = client.GetDatabase("sample_mflix").GetCollection<Playlist>("playlist");
List<string> movieList = new List<string>();
movieList.Add("1234");
playlistCollection.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:
// Previous code here ...
FilterDefinition<Playlist> filter = Builders<Playlist>.Filter.Eq("username", "nraboy");
List<Playlist> results = playlistCollection.Find(filter).ToList();
foreach(Playlist result in results) {
Console.WriteLine(string.Join(", ", result.items));
}
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:
// Previous code here ...
FilterDefinition<Playlist> filter = Builders<Playlist>.Filter.Eq("username", "nraboy");
// Previous code here ...
UpdateDefinition<Playlist> update = Builders<Playlist>.Update.AddToSet<string>("items", "5678");
playlistCollection.UpdateOne(filter, update);
results = playlistCollection.Find(filter).ToList();
foreach(Playlist result in results) {
Console.WriteLine(string.Join(", ", result.items));
}
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:
// Previous code here ...
FilterDefinition<Playlist> filter = Builders<Playlist>.Filter.Eq("username", "nraboy");
// Previous code here ...
playlistCollection.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:
using MongoDB.Driver;
MongoClient client = new MongoClient("ATLAS_URI_HERE");
var playlistCollection = client.GetDatabase("sample_mflix").GetCollection<Playlist>("playlist");
List<string> movieList = new List<string>();
movieList.Add("1234");
playlistCollection.InsertOne(new Playlist("nraboy", movieList));
FilterDefinition<Playlist> filter = Builders<Playlist>.Filter.Eq("username", "nraboy");
List<Playlist> results = playlistCollection.Find(filter).ToList();
foreach(Playlist result in results) {
Console.WriteLine(string.Join(", ", result.items));
}
UpdateDefinition<Playlist> update = Builders<Playlist>.Update.AddToSet<string>("items", "5678");
playlistCollection.UpdateOne(filter, update);
results = playlistCollection.Find(filter).ToList();
foreach(Playlist result in results) {
Console.WriteLine(string.Join(", ", result.items));
}
playlistCollection.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.
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.
A video version of this tutorial can be found below.
This content first appeared on MongoDB.