Less Than 30 Lines Of Code - MongoDB with Testcontainers in C#
April 1, 2024
• 798 views
mongodbmongodb tutorialmongodb atlashow to install mongodbmongodb compassmongodb installationinstall mongodbmongodb c# insertmongo dbmongodb universitymongo db atlasmongodb lecturemongodb atlas databasemongodb trainingmongodb C#mongodb bulk update upsertmongodb upsert c#mongodb c# upsertc# mongodb upsertmongodb upsertc# mongodb drivermongodb csharpC#dockertestcontainerstest containersdotnet dockerdatabase testingdotnet
MongoDB is an awesome document database that we can use from C# using the MongoDB Driver NuGet package. But what if you don't want to setup MongoDB Compass or deal with MongoDB Atlas? Is there an easy solution to just try out MongoDB locally, or even leverage it for testing purposes?
Testcontainers for MongoDB is the easy solution here! See how we can hook up Docker with MongoDB in less than 30 lines of pain-free C# code!
View Transcript
if you watched my other mongod DB Videos and found yourself asking Nick I really don't want to get Compass set up I don't want to deal with Atlas and all this other stuff I just want to be able to start playing around with mongod DB or perhaps you're already interested in mongodb and you're trying to write tests and have things working locally this video is going to be for you hi my name is Nick centino and I'm a principal software engineering manager at Microsoft in this video we're going to be looking at using test containers to set up and run mongodb instances locally in Docker containers if you get comfortable using test containers it's a super awesome way to have stuff running locally to play around with and of course if you're interested in testing as the name suggest you can spin up these containers
for different dependencies and have them operate alongside your test a quick reminder to check that pin comment for my free Weekly Newsletter and my cours is on dome train and with that said let's jump over to the code and check this out so I'd like to start off with the dependencies that we're going to use here so we have two nougat packages for this example we're going to leverage we're going to have mongod DB driver which is what we've been using in the previous videos that I put out on this this is going to be the nougat package that gives us the classes where we can connect to a mongodb database and do things like read write and all the other fancy stuff that you would ever want to do with the mongodb database the other package that we have here is test containers and
then the mongod DB flavor of it so when you grab this it will get the base test container stuff that you need to use as well so you can just grab this mongod DB test containers you get package here the other thing that you're going to want to have is Docker installed on your computer so I have Docker desktop running if I don't have this running when we go to execute the code it's going to have issues trying to spin up Docker containers because there's nothing listening to be able to spin up those containers for us now this might seem like it's a little bit complicated but once we have this running we don't have to worry about anything and I'm sure there's headless versions of this that you could be going to run so even for me I can go collapse this and minimize
it and not have to see the user interface but I'm not familiar with a lot of the different ways that you can go run Docker I always just kind of have this running in the background somewhere and when I don't ever want to see it I just close it and have it minimized to the taskbar so you can look into this more especially if you're doing test runs and you don't want to have a user interface running on the computer but for me this is just the only thing that I had to install for Docker to be working on my computer and it's just Docker desktop you can see in the top left here so I'm going to pull this up later when we start running these examples and that you can see what's going on when we go to execute this okay and now
to look at some code I've just zoomed out a little bit further so you can see that this is an entire program that's going to get a container spun up and torn down for us automatically we're going to be able to connect that database insert a document and read it back that's all fitting on the screen right now and then we'll go through it in a little bit more detail here so to start with in order to get a mongod DB container started up for us we just use the code from Line 6 to9 here to get the container created you can see that I'm using a mongod DB Builder and then we can ask for the specific image that we want to use for that Docker instance if I just use colon latest it's always going to pull down the latest version of the
mongod DB container there are lots of other customization options that we can use on this Builder pattern so if you wanted to explicitly set the ports you can do that there's lots of other things you can configure but just to keep things simple I'm just going to use build to build the container we're not even going ask for any explicit Port binding here because we don't have to in our instance we can just run it and it's going to work automatically for us which is super cool so once we create that container you can see on line 10 we go and start it there's a start async method that we can call so there's a nice async API for us to use and from there what's awesome about this is that the container is up and running we don't have to do anything else magical
to get it to work this will start it up and then we can start to use it basically right after so I'm going to show you from line 12 and on that we can start to use the mongod DB driver nugate package just to be able to get a client ask for the database and start working with the collection because at this point we don't even need to be dealing and worrying about the container running because on line 12 we can ask the container itself for the connection string in my opinion this is one of the most powerful parts and that's why we don't have to worry about setting up a specific port or doing anything else we can just ask the container once it's up and running give me the connection string to mongod DB that's in inside of the container that's running and
it gives it to us no other fancy magic that has to happen and we get a mongod DB client that can talk to mongod DB in that container so that's what's happening on line 12 from there onward line 13 and 14 we're just going to get a test database and create a collection so when we asked for this collection called test what we're doing at that point is basically saying give us the collection or we're going to create one after this when we start interacting with it and maybe I'll give these slightly more unique names so there's no confusion about what's happening here so call this test DB and this one will be test collection so now we have those two as unique names uh just so that you don't think they have to be the same now from here I'm going to insert a
document it's going to be just a very basic Json document that has a single property in it called name and I'm going to assign the name Nick centino just because I'm very not creative and that's my own name so nice and simple from there we're going to ask the collection to find a document and we're just going to give it an empty filter if you haven't watch my previous videos on this I explain how you can go create more complex filters and an or them together but in this case there's only one document if we pass it an empty filter it should match on anything and everything and because there's only one document we can get away with calling this and getting that single document back from there I'm just going to write to the console that we found it and then we can use
dispose a sync on this container and wait to see what we get so technically that's less than 30 lines of code with some console right lines and some com M and some spacing in the code as well so not a lot of code to be able to get up and running with a local database it's important to note that when you close this off it will tear down the entire database you lose everything but I'm pretty sure that if you wanted to do something a little bit more interesting and persist data that there are some settings that you can use with this but I'm not doing that in all of my testing I never do that because I just want to have a very isolated instance of mongod DB or other services running so with that all set and out of the way let's go
run this see what it does because I want to prove to you that it really is this easy to be able to have a local instance of running and start working with it we'll do a quick check in Docker desktop to see that I have nothing running here I go back and press play and I want to pull up Docker desktop as well while this starts you can start to see these two containers spin up in the back I'm going to explain that in just a moment uh test containers is printing all this other stuff to the console so if you recalling the code I wrote I did not have this many console right lines but I did have this found document line so you can see that we ended up finding that document that we inserted and when we write that to the console
it just has this object ID and this name that I set the object ID itself is built in that's not something I sent manually it's just built in when we go to WR and then beyond that I have press enter to exit that's the only other line that I wrote um this delete Docker container gets printed when we start to dispose of things now you'll notice too that we still have one of these two containers running and you might also be asking well why were two containers running right we said let's get a mongod DB container spun up what the heck is this other one well the way that this ends up working behind the scenes is that they have another container to be able to monitor the processes that are running and that way they can close things off when you don't need to
use it anymore so if I go ahead back here if I press enter to exit close all of this off we should start to see that this goes away because there's nothing else to be running and there we go after a few seconds it clears away I didn't take any other action aside from closing down my process and this same behavior happens when you're using tests from visual studio so if you spin up tests or using test containers mongod DB or some other container that you want to go run when your tests all finish off these containers will all close out you don't have to do any manual cleanup and I did mention that if you wanted to be writing tests with mongodb that test containers is an awesome way that you can go do this but what are other use cases aside from just
playing around locally or running tests well another situation is going to be with running benchmarks so if you're interested in seeing that when this video is ready you can watch it here next thanks and I'll see you next time
Frequently Asked Questions
What are the prerequisites for using MongoDB with Testcontainers in C#?
To use MongoDB with Testcontainers in C#, you'll need to have Docker installed on your computer, specifically Docker Desktop. Additionally, you'll need to install two NuGet packages: the MongoDB driver and the Testcontainers package for MongoDB.
How does Testcontainers simplify working with MongoDB for testing?
Testcontainers allows me to easily spin up and tear down MongoDB instances in Docker containers for testing purposes. This means I can run tests against a fresh database without worrying about any setup or cleanup, as the containers are automatically managed.
What happens to the data in the MongoDB container after I close the application?
These FAQs were generated by AI from the video transcript.When you close the application, the MongoDB container is disposed of, and all data within it is lost. If you want to persist data, there are settings you can use, but for testing, I typically prefer isolated instances where data doesn't persist.
