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.
Add MongoDB driver packages using Nuget Packages.
Now you are able to see the reference DLL related to MongoDB.
- Create one class MongoHelper.
- public class MongoHelper<T> where T : class
- {
- public MongoCollection<T> Collection { get; private set; }
-
- public MongoHelper()
- {
- var con = new MongoConnectionStringBuilder("server=127.0.0.1;database=galary");
-
- var server = MongoServer.Create(con);
- var db = server.GetDatabase(con.DatabaseName);
- Collection = db.GetCollection<T>(typeof(T).Name.ToLower());
- }
- }
This class has a connection created to MongoDB.
- Create one class MobileService.
This class has the actual CRUD logic implementation to interact with MongoDB.
- public class MobileService
- {
- private readonly MongoHelper<Mobile> _mob;
-
- public MobileService()
- {
- _mob = new MongoHelper<Mobile>();
- }
-
- public void Create(Mobile mob)
- {
- _mob.Collection.Save(mob);
- }
-
- public void Edit(Mobile mob)
- {
- _mob.Collection.Update(
- Query.EQ("_id", mob.MobileID),
- Update.Set("Name", mob.Name)
- .Set("Details", mob.Details));
- }
-
- public void Delete(ObjectId postId)
- {
- _mob.Collection.Remove(Query.EQ("_id", postId));
- }
-
- public IList<Mobile> GetMobiles()
- {
- return _mob.Collection.FindAll().ToList();
- }
-
- public Mobile GetMobile(ObjectId id)
- {
- var mob = _mob.Collection.Find(Query.EQ("_id", id)).Single();
-
- return mob;
- }
- }
- The class Mobile is the model for the data interaction.
- public class Mobile
- {
- [BsonId]
- public Guid ID { get; set; }
- public int MobileID { get; set; }
- public string Name { get; set; }
- public string Details{ get; set; }
- }
- Using the following code you can add a new item.
- serv.Create(new Mobile { ID= Guid.NewGuid(), MobileID = 1, Name = "Apple", Details = "Testing Application" });
- Using this code you can retrieve all the data records from MongoDB.
- 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.
Now call the MongoDB code from the Controller as in the following:
- public ActionResult Index()
- {
- MobileService serv = new MobileService();
- var datalst = serv.GetMobiles();
- TempData["recordcount"] = datalst.Count;
- return View(datalst);
- }
The Web page looks as in: