In this tutorial, I’ll show you how to use MongoDB with Asp.Net MVC.
Before start, Let’s know about MongoDB.What is MongoDB ?
MongoDB is document oriented database, Where Records are stored as documents.Is it also called as NOSQL database.
MongoDb stores the data in the form of document which is similar to JSON , Known as BSON.
BSON : BSON is a binary representation of JSON with additional type information.
Terms related to MongoDB.
- Collection : A collection is a group of related documents that have a set of shared common indexes. Collections are analogous to a table in relational databases.
-
Documents : Document is set of Key-value pair.
here is Document Sample
1234{
Name :
"Amit"
,
Email :
"amitverma0511@gmail.com"
}
-
A document-based data model. The basic unit of storage is analogous to JSON.
This is a rich data structure capable of holding arrays and other documents. - No schema migrations. Since MongoDB is schema-free, your code defines your schema.
- Replication is very easy.
- You can perform rich queries. More on MongoDB
First of all Download the MongoDB.
How to Install MongoDB.
After installing MongoDb in your system .
Create Database in MongoDb.
Here I’m creating Database name as “School“.Execute the following command in Mongo Shell.
1
| use School |
Insert records in School Database .
Create an array which contains list of name of student.using for loop we will insert records.
1
2
3
4
| var Name=[ "Amit" , "Rohit" , "Ajay" , "Sumit" , "Rahul" ]; for (i=0 ;i<5;i++){ db.Students.insert({Name : Name[i]}); } |
Now you see the inserted records by using following query.
1
| db.Students.find() |
So far we have created Database and Inserted records in it.
Now let’s learn how to connect MongoDb with C#.
Download C# Driver for MongoDB
Extract the Zip file (if you have downloaded the .Zip file)
In Extracted folder, you will get two .dll file
- MongoDB.Bson.dll
- MongoDB.Driver.dll
Add the the reference of those two dll file.
Right click on Reference => Add Reference => Browse
Add a Model Class Students.
01
02
03
04
05
06
07
08
09
10
11
| using MongoDB.Bson; namespace MvcWithMongoDb.Models { public class Students { public ObjectId Id { get ; set ; } public string Name { get ; set ; } } } |
Create constructor of HomeController.
01
02
03
04
05
06
07
08
09
10
11
12
13
| private MongoDatabase mongoDatabase; public HomeController() { // create connectionstring var Client = new MongoClient(connect); // get Reference of server var Server = Client.GetServer(); // get Reference of Database mongoDatabase = Server.GetDatabase( "School" ); } |
Mongo Client will interact with the server, so using MongoClient instance , call the GetServer method.
Now to Access the database of MongoDb, I have used this instance of Server.
Now Create Method which will return Json Type result.
01
02
03
04
05
06
07
08
09
10
11
| public JsonResult GetAll() { var collections = mongoDatabase.GetCollection<Students>( "Students" ); IList<Students> students = new List<Students>(); var getStudents = collections.FindAs( typeof (Students), Query.NE( "Name" , "null" )); foreach (Students student in getStudents) { students.Add(student); } return Json(students, JsonRequestBehavior.AllowGet); } |
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
| using System.Collections.Generic; using System.Web.Mvc; using MongoDB.Driver; using MongoDB.Driver.Builders; using MvcWithMongoDb.Models; namespace MvcWithMongoDb.Controllers { public class HomeController : Controller { private MongoDatabase mongoDatabase; public HomeController() { // create connectionstring var Client = new MongoClient(connect); // get Reference of server var Server = Client.GetServer(); // get Reference of Database mongoDatabase = Server.GetDatabase( "School" ); } public ActionResult Index() { return View(); } public JsonResult GetAll() { var collections = mongoDatabase.GetCollection<Students>( "Students" ); IList<Students> students = new List<Students>(); var getStudents = collections.FindAs( typeof (Students), Query.NE( "Name" , "null" )); foreach (Students student in getStudents) { students.Add(student); } return Json(students, JsonRequestBehavior.AllowGet); } } } |
write the following code.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
| < link href = "~/Content/bootstrap.css" rel = "stylesheet" /> < script src = "~/Script/jquery-2.1.1.min.js" ></ script > < script src = "~/Script/School.js" ></ script > < div id = "divList" > < p > < img src = "~/Content/images/images.jpg" /> </ p > < table class = "table table-bordered" id = "tblList" > < tr > < th colspan = "2" style = "text-align:center;" >Student List</ th > </ tr > < tr > < th > SNo.</ th > < th >Name</ th > </ tr > </ table > </ div > |
write the following code in School.js.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
| $(document).ready( function () { GetAll(); }); function GetAll() { $.ajax({ type: 'GET' , contentType: 'application/json; charset=utf-8' , url: 'Home/GetAll' , success: function (data) { var genHtml = "" ; $.each(data, function (index, value) { genHtml += "<tr><td>" +(index+1)+ "</td><td>" + value.Name + "</td></tr>" ; }); $( '#tblList' ).append(genHtml); }, error: function (data) { alert( 'Error in getting result' ); } }); } |
Demo
DOWNLOAD
No comments:
Post a Comment