Connect to MongoDB from .NET using Web API

Posted by: Suprotim Agarwal , on 5/20/2013, in Category ASP.NET
Views: 55150
Abstract: A walkthrough of how to sign up with MongoHQ to setup a MongoDB database and then connect to it from an ASP.NET Web API application.

MongoDB is a popular NoSQL Database with a fast growing user base as well as feature list. MongoDB can be downloaded and Installed for free from here. If you don’t want to install MongoDB for experimenting, you can use one of the Hosted Providers. In this demo we’ll use MongoHQ so we’ll start with setting up a MongoDB on MongoHQ

 

Getting Started with MongoHQ – MongoDB in the Cloud

To get started with MongoHQ we’ll have to Sign Up first. So in the next few steps, we’ll go from Signup all the way to creating a Database.

Step 1: You enter the following information first.

image

Step 2: When you click on Create Account, it moves to the next step where it asks for Credit Card Information, but that’s optional and you can skip it to try out the free version for now.

credit-card-info

Step 3: At this point, you will be presented with a screen to create your database. Don’t do it yet. On the Top Right corner of your screen you will see your account name, pull it down and click on the Account Settings.

account-settings

It is important that you setup the Default Database User first. Give it a username and password and remember these two e.g. (administrator/password).

create-super-user

Step 5: Now you can click on the Create Database button on the top right to navigate to the New Database screen.

add-database

Step 6: In the New Database page, select the Host and the Type you want. I selected the 512 Mb option which is free at the moment. You also have to specify your Database name e.g. MyFirstDb. Click on Create Database to complete the DB Creation process.

new-mongodb-database

Once it completes, you’ll see a dialog as the following:

my-first-db-ready

Step 7: Note the Mongo URI, you’ll need this later. Our MongoDB instance is now ready for use.

Setting up the Web API

Now that we have got an Instance of MongoDB to talk to, we can setup our Web API and send/retrieve data from it.

Step 1: Create a new MVC 4 project with the Basic template (or the Web API template).

Step 2: Add an Empty WebAPiController called MongoDbController.

image

Step 3: In the Web.Config, add the connection string from Step 7 above. You have to include the User Name and Password as follows:

<add name="MongoHQ" connectionString="mongodb://administrator:xxxxxxxx@widmore.mongohq.com:10010/MyFirstDb" />

Replace the ‘xxxxxxxx’ with your plaintext password.

Step 4: Install MongoDB Drivers from Nuget using the following command

PM> Install-Package mongocsharpdriver

Step 5: In the MongoDbController, add a field for the MongoDatabase and initialize it using the RetrieveMongohqDb method.

readonly MongoDatabase mongoDatabase;

public MongoDbController()
{
mongoDatabase = RetreiveMongohqDb();
}

The RetrieveMongohqDb method simple instantiates a MongoClient using the connection string we added to the Web.Config. Next we retrieve the MongoServer using the mongoClient and finally pull out the database (MyFirstdb) from the server. This ensures everytime the Controller is invoked, the MongoDb is ready for us. Ideally this will go in a Repository. This is just demo code.

private MongoDatabase RetreiveMongohqDb()
{
MongoClient mongoClient = new MongoClient(
    new MongoUrl(ConfigurationManager.ConnectionStrings    
     ["MongoHQ"].ConnectionString));
MongoServer server = mongoClient.GetServer();
return mongoClient.GetServer().GetDatabase("MyFirstDb");
}

Step 6: Add a model entity or as referred to in case of MongoDB a document with the following attributes:

public class Contact
{
[BsonId]
public string Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
}

The BsonId attribute is provided by the MongoDb driver and converts a string into an Id that MongoDB understands while saving, and converts it back to a string while loading/reading data.

Step 7: Implementing the Get All request - We’ll create a Get Method that retrieves all the Contacts from the Database. Since we are using WebApi Controller, we simply return the enumerable collection of data returned. The returned Enumerable is converted into a List of Contact objects.

public IEnumerable<Contact> GetAll()
{
List<Contact> model = new List<Contact>();
var contactsList = mongoDatabase.GetCollection("Contacts").FindAll().AsEnumerable();
model = (from contact in contactsList
  select new Contact
  {
   Id = contact["_id"].AsString,
   Name = contact["Name"].AsString,
   Address = contact["Address"].AsString,
   Phone = contact["Phone"].AsString,
   Email = contact["Email"].AsString
  }).ToList();
  return model;
}

Step 8: Creating or Updating a Contact – Next we add an HttpPost method that accepts a Contact object and depending on whether it has an Id, either creates a new one, or updates the existing one. The code for this is as follows:

public Contact Save(Contact contact)
{
var contactsList = mongoDatabase.GetCollection("Contacts");
WriteConcernResult result;
bool hasError = false;
if (string.IsNullOrEmpty(contact.Id))
{
  contact.Id = ObjectId.GenerateNewId().ToString();
  result = contactsList.Insert<Contact>(contact);
  hasError = result.HasLastErrorMessage;
}
else
{
  IMongoQuery query = Query.EQ("_id", contact.Id);
  IMongoUpdate update = Update
   .Set("Name", contact.Name)
   .Set("Address", contact.Address)
   .Set("Phone", contact.Phone)
   .Set("Email", contact.Email);
   result = contactsList.Update(query, update);
   hasError = result.HasLastErrorMessage;
}
if (!hasError)
{
  return contact;
}
else
{
  throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
}

Ideally we can break the persistence logic which should be in a Repository and we should break this method up into two, one for Insert and one for Update. The condition for Insert is simple, if the incoming Contact doesn’t have an Id, create a new Id and send it to Server. If the incoming contact has an Id, create an instance of IMongoQuery object using keyed on the contact.Id. We then set the properties that need to be updated in the IMongoUpdate instance.

Finally the contactsList collection fires the Update using the query and update instances. We can verify a successful update but checking for result.HasLastErrorMessage.

That’s about all the code we have. We don’t have a UI so we’ll use Fiddler to do our Testing.

Testing our Web API

Run the application, it will show a YSOD saying Resource cannot be found.

Navigate to the /api/MongoDb/ URL (e.g. http://localhost:61093/api/MongoDb/). IE will download the Json. First time around the Json array is empty.

empty-json

Next we use Fiddler Composer to compose a PUT request and send a Contact info in JSON format.

put-new-contact

Now if we do a Get again, we’ll see the Json returns with the following data.

image

Finally we compose another POST in Fiddler and change the Name from Suprotim to Supro and Post it. At the backend, the execution goes to the else path because this time it has an Id associated. As a result the Contact is now updated.

You can verify the same from MongoHq’s dashboard as well. Cool!

Conclusion

Mongo DB is getting popular as a NoSql Document database specially where fast storage and retrieval is important but reporting is not a criteria. Today we scraped the surface of how we can connect to Mongo DB from .NET using Web API. We used a free Hosted Solution. In future we will investigate how to do this on a local MongoDB instance as well.

Download the entire source code of this article (Github)

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Reegan Durai on Thursday, June 13, 2013 7:50 AM
Hi,
  I am also using mongodb. But list of document fetching array spend a lot of time.for example one with 50 document got 345 miliseconds.please help How to solve it?
Comment posted by Antonio Di Motta on Wednesday, March 5, 2014 2:32 AM
Is there a way to connect using ssl? Without encryption is unuseful for real applications.
Actually I have a .net web site on AppHarbor and using Mongolab for strorage, in this case I use a direct connection (without http) because all services work on AWS instrastructure.
Comment posted by Smith Cole on Wednesday, April 15, 2015 3:36 AM
Your post is so good. I am wondering how I can be notified whenever a new post has been made.I really like your information. Yes, MongoDB is a popular NoSQL Database and connect to it from an ASP.NET Web API application. here you describe all the details about this... thanks a lot for the valuable information.actually I have no idea about this but at that time, while I look myasp.net I have an interest to know all about.