Querying Mongodb with ASP.NET MVC
The following example shows how to query mongodb using ASP.NET MVC projects.
Mongodb community offers drivers to facilitate the integration between ASP.NET and mongo, all drivers are available in NuGet Package Manager, you can find all references here.
The following tutorial shows how to install Mongodb: Installing MongoDB.
You can run the mongo server using the following command:
C:\mongodb\bin\mongod.exe --dbpath C:\mongodb_env\data
the dbpath parameter defines the path of mongo database.
The project manages some contact informations like name, email, website.
Firstly, you need to create a new ASP.NET MVC 4 Basic project and add following NuGet packages to your solution:
The following image shows the structure of the demo project:
- ContactController.cs: manages all views and it initialize the Contact collection.
- ContactCollection.cs: initializes the connection to mongodb and it implements all CRUD operations on the Contact collection.
- MongoDBRepo.cs: defines the url to mongodb and it initializes the MongoClient object.
- Contact.cs: defines our domain model.
- Views folder contains List.cshtml, Edit.cshtml and Create.cshtml.
Define the model
The following snippet shows the Contact.cs implementation:
Define repository classes
The MongoDbRepo.cs and ContactCollection.cs files contain the code that describes the communication between the mongodb Collection and the project. MongoDbRepo.cs creates the connection to the server and define the database of project:
The following code is written inside ContactCollection.cs, and defines some query over the Contact Collection:
Controller action methods
The controller will initialize a new instace of ContactCollection class, and every action method will call the corresponding querying method:
Create, update and list views
All the views are available at the following url: https://github.com/samueleresca/Blog.QueryingMongoDb, they are strongly-typed views that are binded on Contact model.