Domain Driven Design with Web API extensions part 9: setting up MongoDb

Introduction

In the previous post we set out the main topic of this new extension to the DDD model project. We said that we would add another repository mechanism, namely MongoDb. We went through the basic idea and some terminology behind MongoDb, e.g. what a document, a collection or an object ID means.

In this post we’ll set up MongoDb locally and try to connect to it from .NET using the MongoDb .NET driver.

MongoDb installation and initial checks

We’ll follow the steps on Windows of course. Navigate to the MongoDb downloads page and click the Windows download link:

MongoDb installation link

Note that the MongoDb version may be different from what you see in the image by the time you read this post.

The link will download an .msi installer. Run the installer, step through it and select the Complete installation on this screen:

Select complete installation of MongoDb

The installer will install the files in the Program Files/MongoDb folder. There should be a subfolder called Server, then 3.0 which includes the bin folder. The bin folder includes the exe files to start the database server – mongod.exe – and the database client – mongo.exe.

We want to be able to reach these executables from the command line easily for our initial tests. We need to extend the PATH environment variable with the full folder path to the bin folder mentioned above.

Open the Environment Variables editor, highlight PATH in the System variables list and click Edit… :

Open the PATH environment variable to add MongoDb subfolder

The Edit System Variable window will open. The PATH variable will already have some list of folder URLs separated by a semicolon ‘;’, e.g.:

C:\ProgramData\Oracle\Java\javapath;%JAVA_HOME%\bin;%MAVEN_HOME%\bin;

If there’s no semi-colon at the end of the string then make sure you put one there. Then paste the full path to the MongoDb server bin folder. I have it on my C: drive so in my case I’ll add the following string after the final semi-colon:

C:\Program Files\MongoDB\Server\3.0\bin

Click the OK buttons to close the environment variables editor and the System Properties window.

MongoDb will by default use a folder called “data” on your C drive to store the documents. So insert a folder called “data” on c:\. Within the “data” folder create another folder called “db”.

Let’s first connect to MongoDb manually. Open a command prompt and issue the following command:

mongod.exe

As we added the full path to the MongoDb bin folder the above command should be found and executed correctly. As mentioned above this exe file will start the MongoDb server. The final message should be that the server is waiting for connections on port 27017:

MongoDb server is waiting for connections

Open up another command prompt, navigate to and start the client by the following command:

mongo.exe

One connection is open in mongo server

You’ll see that the client has managed to connect to a database called “test”. That’s the default database that the client will connect to in MongoDb.

So we managed to connect to the MongoDb engine from a client. You can write direct JavaScript commands in the client to create databases, collections, insert documents etc. I will not go through these operations here – I promised to keep the MongoDb-related technical stuff to a minimum and writing JavaScript commands with a lot of JSON is not within the scope of this series. However, if you’re interested in those direct commands then you can check out the official manual. Also, as hinted at before we’ll go through MongoDb in a greater detail later on in 2016 in a dedicated series.

You can close the client but make sure that the server is up and running in its command window. Note that the MongoDb server can be installed as a Windows service. Normally it’s not convenient having to start the DB engine all the time we want to talk to it. However, we won’t do it here. If you’re interested then you can find the required steps here. Check out the section called “Configure a Windows Service for MongoDB”.

Connecting from .NET

Recall that we had a demo database tester C# console application in the DDD skeleton project. We’ll follow the same path to test MongoDb.

This is what the structure of the demo project looks like after the previous extension series:

Project structure before adding MongoDb sections

Add a new C# console application called MongoDbDatabaseTester to the project. Right-click on it and set it as the startup project.

Add the following MongoDb .NET driver from NuGet to the console application:

Add MongoDb driver from NuGet

Insert the following code to Main in Program.cs:

string mongoDbConnectionString = "mongodb://localhost:27017";
MongoClient mongoClient = new MongoClient(mongoDbConnectionString);
IMongoDatabase testDatabase = mongoClient.GetDatabase("Cartoons");
Task t = testDatabase.CreateCollectionAsync("Disney");
Task.WaitAll(t);

As you see MongoDb also needs connection strings just like when connecting to an MS SQL database. The example presented above is probably as easy as it gets: we’re connecting to the local MongoDb server on the default port 27017. More realistic connection strings might be much longer with other properties such as authentication, server names in a server cluster, read and write policies etc. For our purposes this is just fine as we’re not aiming to become MongoDb professionals in this series.

We then build a client which can connect to the server with that connection string. Next we use that client to get hold of a database called Cartoons. MongoDb is a very flexible database. It doesn’t make any difference whether the database Cartoons exists or not. It will be created for you as soon as you insert a collection to it. This goes for collections as well: you can get hold of a collection and MongoDb won’t complain if it doesn’t exist. It will be created as soon as you insert a document in it.

Finally we create a collection called Disney. Most functions in the MongoDb driver are awaitable ones that return a Task. As we cannot modify the signature of Main we have to resort to this Task.WaitAll solution.

If you run the code then you should see that the MongoDb server has acknowledged the connection and then also noted the end of it:

MongoDb server acknowledged connection from .NET driver

Your output will probably differ but there should be a command similar to the one highlighted above. It summarises the Cartoons and Disney creation commands.

We can actually test if the database and collection were created from the mongo client console. Follow the commands highlighted below:

Verifying if .NET MongoDb driver commands succeeded

Great, we have laid the foundations for building the full load testing domain repository based on MongoDb.

We’ll continue in the next post.

View the list of posts on Architecture and Patterns here.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

One Response to Domain Driven Design with Web API extensions part 9: setting up MongoDb

  1. Pingback: Domain Driven Design with Web API extensions part 9: setting up MongoDb | Dinesh Ram Kali.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: