In Focus

Interacting MongoDB using .NET Web API

In this article you will learn how to interact MongoDB using .NET Web API.

MongoDB is a popular NoSQL database that makes it a great backend for Web APIs that lend themselves towards a document store rather than a relational store. In this article we show how to use MongoDB with the ASP.NET Web API to build an ApiController with support for HTTP GET, PUT, POST and DELETE.

This sample project gives an idea of how to access MongoDB using .Net WebAPI.

First of all setup the environment in your local machine:

First create a Web API using Visual Studio.

Add one Class Library project to implement the MongoDB interaction.

web application

Add MongoDB driver packages using Nuget Packages.

Nuget Packages

Now you are able to see the reference DLL related to MongoDB.

DLL

  1. Create one class MongoHelper.
    1. public class MongoHelper<T> where T : class  
    2. {  
    3.     public MongoCollection<T> Collection { getprivate set; }  
    4.   
    5.     public MongoHelper()  
    6.     {  
    7.         var con = new MongoConnectionStringBuilder("server=127.0.0.1;database=galary");  
    8.   
    9.         var server = MongoServer.Create(con);  
    10.         var db = server.GetDatabase(con.DatabaseName);  
    11.         Collection = db.GetCollection<T>(typeof(T).Name.ToLower());  
    12.     }  
    13. }  
    This class has a connection created to MongoDB.

  2. Create one class MobileService.

    This class has the actual CRUD logic implementation to interact with MongoDB.
    1. public class MobileService  
    2. {  
    3.     private readonly MongoHelper<Mobile> _mob;  
    4.   
    5.     public MobileService()  
    6.     {  
    7.         _mob = new MongoHelper<Mobile>();  
    8.     }  
    9.   
    10.     public void Create(Mobile mob)  
    11.     {  
    12.         _mob.Collection.Save(mob);  
    13.     }  
    14.   
    15.     public void Edit(Mobile mob)  
    16.     {  
    17.         _mob.Collection.Update(  
    18.             Query.EQ("_id", mob.MobileID),  
    19.             Update.Set("Name", mob.Name)  
    20.                 .Set("Details", mob.Details));  
    21.     }  
    22.   
    23.     public void Delete(ObjectId postId)  
    24.     {  
    25.         _mob.Collection.Remove(Query.EQ("_id", postId));  
    26.     }  
    27.   
    28.     public IList<Mobile> GetMobiles()  
    29.     {  
    30.         return _mob.Collection.FindAll().ToList();  
    31.     }  
    32.   
    33.     public Mobile GetMobile(ObjectId id)  
    34.     {  
    35.         var mob = _mob.Collection.Find(Query.EQ("_id", id)).Single();  
    36.   
    37.         return mob;  
    38.     }          
    39. }  
  3. The class Mobile is the model for the data interaction.
    1. public class Mobile  
    2. {  
    3.      [BsonId]  
    4.     public Guid ID { getset; }  
    5.     public int MobileID { getset; }  
    6.     public string Name { getset; }  
    7.     public string Details{ getset; }          
    8. }  
  4. Using the following code you can add a new item.
    1. serv.Create(new Mobile { ID= Guid.NewGuid(), MobileID = 1, Name = "Apple", Details = "Testing Application" });  
  5. Using this code you can retrieve all the data records from MongoDB.
    1. var datalst = serv.GetMobiles();  

For testing the application first start the MongoDB service on your local system.

Please use the following procedure to start MongoDB.

Go to the command prompt:

C:\MongoDB\bin>mongod and press Enter.

Then MongoDB service is started.

Please find the following screenshot.

cmd

Now call the MongoDB code from the Controller as in the following:

  1. public ActionResult Index()  
  2. {  
  3.     MobileService serv = new MobileService();  
  4.     var datalst = serv.GetMobiles();  
  5.     TempData["recordcount"] = datalst.Count;              
  6.     return View(datalst);  
  7. }  
The Web page looks as in:

page