Using MongoDB with ASP.Net MVC

In this post I am going to demonstrate with a hands-on example how to use the popular NoSQL database MongoDB to store and retrieve data using Visual Studio 2015and ASP.Net MVC.

When creating an application, any type of application (web, windows, distributed) all the data is stored and retrieved from a database. The most popular kind of databases that we are using to store and retrieve data are called Relational Databases and I have been using SQL Server as the RDBMS of choice for many years now. Data grows fast nowadays. We are having more applications than ever and databases grow rapidly.

That fact alone has some serious implications. There is more demand for scale and speed. When you design a web application, a commercial web application e.g an ecommerce store, you know that the speed and scale of the e-shop will mean more customer conversions for your client.

It is the demand for scale, speed, and fast application development that has brought on a new breed of databases, namely NoSQL databases. MongoDB is the fastest growing NoSQL databases out there.

If you need scalability and speed in an application, this NoSQL database really shines.

MongoDB is open source software. MongoDB is written in C++. It's available in 32 and 64-bit distributions. It is available in Linux 32-bit and the Windows 32-bit distributions. In a production environment you cannot use 32-bit distributions for obvious reasons. It is a document based database and has drivers for many programming languages. 

You can find more (download it) in the website can find whitepapers, webinars e.t.c. There are also online courses - The latest release is MongoDB 3.2.

Relational databases save data in tables and rows.Programmers develop applications using object oriented languages. The objects we use are simply not tables and rows. In order to overcome this impedance we write a mapping layer, or use an ORM (Entity Frameowork is the ORM I use) to translate between objects in memory and what is stored in the database.

So what is so different in MongoDB and in NoSQL dbs in general? Well, in MongoDB, there is no schema to define. There are no tables and no relationships. There are only documents. Every document you save in MongoDB can be as simple, or as complex as your application requires. 

As a developer you do not have to explicitly create databases, tables and columns.

Documents can have embedded documents and collections. They can have any structure you can imagine, much like the objects you create when using object-oriented programming languages ( ). You do not need a separate table for Customer, their Orders and their Addresses. Everything is nested within the customer document itself. There are not foreign keys and you need not to worry about foreign keys and the integrity of relationships between tables.

You dot not model your code according to the data store requirements, design, limitations and nature. Instead of that the data store will fit your code and the application's requirements.

When developing modern web applications, you've likely used JSON. MongoDB uses BSON, very similar pattern to JSON, to store documents. So you will feel very familiar with MongoDD if you are familiar with JSON. More on BSON you can find in this site - . You can start b y reading the FAQ - 

MongoDB uses GridFS for storing, querying, and associating files with data in the application.

Looking into the DB-engine site we can see that MongoDB is the 4th most popular storage system,

Let's move now to the hands-on example.

1) First, we need to install MongoDB. You can download it here ( ) and you can see installation instructions for Windows here, 

2) I downloaded the mongodb-win32-x86_64-2008plus-ssl-3.0.7-signed.msi and installed MongoDB easily on my Windows 8.1 Enterprise edition. The D:\mongodb\bin folder contains all the .exe for the MongoDB to run properly. More specifically

Server - mongod.exe
Router - mongos.exe
Client - mongo.exe

3) I create a db folder in the path D:\data\db. MongoDb requires a data directory.

I start MongoDB server from the command prompt by changing to the installation directory and type D:\mongodb\bin\mongod.exe  - The waiting for connections message in the console output indicates that the mongod.exe process is running successfully.

4) To connect to MongoDB through the mongo.exe shell, open another Command Prompt window, D:\mongodb\bin\mongo.exe.  

I have started MongDB.

Have a look at the picture below

5) I am creating a database with the name "Football" by typing in the command prompt window 

Use football

6) Now I need to populate, insert records in the database - have a look at this link - 

As we said earlier MongoDB stores data in the form of documents, which are JSON-like field and value pairs.

In the Command Prompt window I type

var Name=["Messi","Ronaldo","Rooney","Torres","Ibrahimovic"];
for(i=0 ;i<5;i++){
db.Footballers.insert({Name : Name[i]});

Now we can see if the rows we inserted were in fact inserted in the MongoDB. 

Type db.Footballers.find() in the command prompt window.

Have a look at the picture below (all the records have been inserted)

7) Now we need to create an ASP.Net MVC application and we will use this simple web application to connect to MongoDB and show these records in a web page.

8) I create a web application in VS (I choose an empty web application) and the name of the project is FootballMVCMongoDB.

9) After VS is creating the ASP.Net empty web application (with MVC in mind - Empty Controllers and Models folder) we need to install the C# MongoDB Driver. We can do that from Nuget. In the Package Manager Console I type "install-Package mongocsharpdriver". The driver is installed and the libraries are added to my project. Have a look at the picture below.

10) Ι am going to add my model class, Footballers.cs in the Models folder.

public class Footballers
public ObjectId Id { get; set; }
public string Name { get; set; }

11) I am going to create an empty HomeController.

I need to modify my controller to connect to the Football db to read the footballer names.

We need to create an instance of the MongoClient.

We add a constructor to this controller.

This is the code for the constructor

 private MongoDatabase database;

public HomeController()

var connectionstring = "mongodb://localhost";
var client = new MongoClient(connectionstring);

 var server = client.GetServer();

database = server.GetDatabase("Football");


Ι have the connection string, then I create an instance of a client to interact with the MongoDB server and then I access the MongoDB database.

12) I need to create Method which will return Json Type result.

public JsonResult GetAll()
var collections = database.GetCollection<Footballers>("Footballers");
IList<Footballers> footballers = new List<Footballers>();
var getFootballers = collections.FindAs(typeof(Footballers), Query.NE("Name", "null"));
foreach (Footballers footballer in getFootballers)
return Json(footballers, JsonRequestBehavior.AllowGet);

I create a collection (collections) and a List of footballers. Then I query the collection for documents that the name is not equal null. Then I populate my list of footballers and specify the return type as JSon.

Have a look here .

13) Then I need to create a view to show the results. In the Views folder I add the folder Home. Then I add the Index.cshtml view inside the Home folder.

Inside the Index.cshtml view I type the following code

<script src="~/Script/jquery-2.1.1.min.js"></script>
<script src="~/Script/Football.js"></script>

<table id="fList">

<th>Number </th>


Then I need to call my server side method that returns JSON from the client. I will use JQuery and I will insert the code in the Football.js in the Script folder in my solution. Inside the Football.js i type the following code.

$(document).ready(function () {

function GetAll()
type: 'GET',
contentType: 'application/json; charset=utf-8',
url: 'Home/GetAll',
success: function (data) {
var newHtml = "";
$.each(data, function (index, value) {
newHtml += "<tr><td>"+(index+1)+"</td><td>" + value.Name +"</td></tr>";
error: function (data) {
alert('Error in getting result');

I just create a method and then call the GetAll method (server-side), get the JSon data back,parse it and append it in a table html element.

14) Build and run your application. The names of the footballers will show up in the screen. Have a look at the picture below.

We have created our first application where we read data from a MongoDB database using ASP.Net MVC. We also downloaded, installed and started MongoDB and inserted records in it. We also talked about the importance and use of NoSQL databases.

You can submit questions or search through answers in the StackOverflow section for MongoDB - 

Hope it helps.

No Comments