Using MongoDB with ASP.NET MVC

Update: While the instructions in this tutorials are still valid, the new version of MongoDB does not recommend using an arbiter.

MongoDB is one of the most popular and fastest growing NoSQL (Not only SQL) providers. Wikipedia defines NoSql as:

A NoSQL or Not Only SQL database provides a mechanism for storage and retrieval of data that is modeled in means other than the tabular relations used in relational databases. Motivations for this approach include simplicity of design, horizontal scaling and finer control over availability. The data structure (e.g., key-value, graph, or document) differs from the RDBMS, and therefore some operations are faster in NoSQL and some in RDBMS

In this series of articles, we will:

  • Download, install and configure MongoDB.
  • Configure MongoDB replications using three databases.
  • Use Onion Architecture to create a Recruitment Agency Application using ASP.NET MVC 5.
Environment Setup:
    1. Download MongoDB (a download link can be for at Make sure to download the zip file matching your machine’s architecture (I downloaded the 64-bit because my computer runs on a 64-bit architecture).
    2. Create a directory called MongoDB under the root of your C:\ drive then extract the bin directory and mongo licenses from the zip file into MongoDB directory. Your final directory should look like the following screen capture:
    3. Create a directory inside MongoDB, name it config, open it and then create the following files inside: Primary.conf, secondary.conf, and arbiter.conf.
    4. Paste the following snippets into their respective files and save the files (commands explanation is at the end of the commands code).


# filename primary.conf
# db path settings
# loging config


# fileName secondary.conf
# db path settings
# loging config


# fileName arbiter.conf
# db path settings
# loging config

Your final config directory should look like the following screen capture:

  1. Create a directory inside MongoDB, name it scripts, open it and then create a .js file and name it replicasetConfig.js. Open the javascript file, copy the following snippet, paste it inside the js file and save it.

    var config ={_id:'StarRecruitment', members:[
    {_id:0, host:'localhost:1001', priority:100},
    {_id:1, host:'localhost:1002', priority:50},
    {_id:2, host:'localhost:1003', arbiterOnly:true}]};

The final directory set up should look like the following screen capture:

Commands Explanation:
.conf file commands (Anything starts with # is a just a comment):

dbpath={Path}: sets the path of MongoDB database
logpath={path}: sets the path where MongoDB writes its logs
logappend={bool}: instructs mongo to append to logs when set to true
verbose={v arguements}: sets MongoDB logging verbosity. 5 v's is the maximum verbosity as it logs everything.
port={number}: sets the port associated with the MongoDB database instance
serviceName={string}: sets the service name when MongoDB is installed as a windows service
replSet={string}: sets the name of the replication set name (replication sets are grouped by this name)

JavaScript Object Explanation:

The script creates a config object to be used when we initialize our replica set members (note the Id here is the same as the relSet argument in the conf files).
The members array sets the id to equal name of the replica set, set the host and port of each database in the replication (the port must match with whatever we set in the .conf files). The priority is used to determine which database has the higher priority in the case of a Failover. The arbiterOnly value flags the instance as an arbiter.


Installing and configuring MongoDB database and replication requires running multiple commands, to speed this up, I created a batch file to use and save you some time.

Save the following snippet anywhere on your machine to a .bat file (name it configureMongo.bat)



REM Configure mongodb database structure
ECHO - Setting up directories
MD C:\mongodb\databases\primary
MD C:\mongodb\databases\secondary
MD C:\mongodb\databases\arbiter
ECHO - Directories setup
REM Create logs directory

MD C:\mongodb\logs
REM Change to mongodb directory
CD C:\mongodb\bin
ECHO - Installing MongoDB servers as Windows Services
REM --Install the primary server as a windows service
mongod --config C:\mongodb\config\primary.conf --install
REM --Install the Secondary server as a windows service
mongod --config C:\mongodb\config\secondary.conf --install
REM --Install the Arbiter server as a windows service
mongod --config C:\mongodb\config\arbiter.conf --install

REM --Start services
ECHO - Starting Services

net start mongodb-serv1
net start mongodb-serv2
net start mongodb-serv3


CD C:\mongodb\bin
ECHO - Removing MongoDB services
mongod --remove --serviceName Mongodb-serv1
mongod --remove --serviceName Mongodb-serv2
mongod --remove --serviceName Mongodb-serv3
ECHO - Removed MongoDB services
CD C:\mongodb

ECHO - Removing databses directories
rmdir /s /q C:\mongodb\databases\
ECHO - Removed directories
ECHO - Removing logs directory
rmdir /s /q C:\mongodb\logs\
ECHO - Removed logs directory


The most important commands inside this batch file are the ones starting with mongod (they install and remove the mongo database services)

To complete the configurations, open command prompt as an administrator, change the directory to where you saved the .bat file and then execute the command passing install as the only argument:

Once the batch file finishes executing, execute the following command "mongo --port 1001 C:\mongodb\scripts\replicasetConfig.js --shell" then type config, then type rs.initiate(config) and hit enter:

After you hit enter, you will see a message similar to this:

        "info" : "Config now saved locally.  Should come online in about a minute.",
        "ok" : 1

Wait for 10 seconds then hit enter again. Your command prompt should look like this:

Now MongoDB is installed, databases and replication is configured. To check the replication status type rs.status() and hit enter. Your screen should be similar to this:

If you get errors, try executing the batch file without the install argument first (this will reset the environment) then re-run the batch file with the install argument (ensure you are running the command prompt as an administrator)

That's it for part one of this series. Next, we will start creating the MVC application.


Comments (2) -

The main reason I gave up on experimenting with Mongodb was the commands I had to type then retype again.It was painful. Your batch file makes things too easy.
Thank you very much, I will be waiting for part 2

You welcome Mark.
Part two will be posted when I have enough time, meanwhile read up on Mongodb and Onion Architecture whenever you get a chance.

Comments are closed