[Coding] Notes on Working Through a MongoDB and .NET Web API Tutorial

Posted by Khatharsis on February 28, 2015

I’ve gone back and forth with learning MongoDB, then losing interest, then learning MongoDB again, then losing interest. It’s a cycle that keeps occuring if there isn’t a meaningful application that gets built with the new technology. I’m crossing my fingers that this time something will get built. But, baby steps first: tutorials.

One of the challenges of the industry’s more recent push for agile this and agile that (yes, sarcasm) is tutorials quickly go out of date. I chose a MongoDB/Web API tutorial because it’s yet another framework I wanted to check out and get a little more familiar with. I found this tutorial written just a couple of days over two years ago. Two years ago. That’s not that long, but in technology time, it’s a pretty long time. Long enough that I had to consult the official document using the MongoDB C# driver to see the non-deprecated methods currently being used.

Unfortunately, the MongoDB/Web API tutorial doesn’t stand well on its own as it’s part of a series, but it wasn’t so bad that I was forced to dissect it line by line. (I’m also not the type of person to download pre-written code files unless I’m so lost and need a reference.) Below are the notes I took while working through it.

Namespaces to include in ContactRepository.cs:


using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using MongoDB.Driver.Linq;

(Note that these namespaces are just for the purposes of this tutorial.)

In Contact.cs, I did not see a need to use the decorator [BsonId] as I got various errors (or I couldn’t find the right reference to include), but it worked fine. Additionally, the official document mentions the Id field is necessary for domain classes (e.g., Contact) if it will be used as a root document.

The up-to-date method of accessing MongoDB is the following:


MongoClient client = new MongoClient(conn);
MongoServer server = client.GetServer();
MongoDatabase db = server.GetDatabase(dbName);
MongoCollection collection = db.GetCollection(collectionName);

Make use of LINQ when getting a specific record. Instead of Query.EQ("_id", id) use:


IMongoQuery query = Query.EQ(c => c.Id, id);

SafeModeResult is deprecated. Use WriteConcernResult.

And one last thing I encountered is a HTML500 error that specifies a parameterless constructor is missing for the controller, but the innermost exceptions suggest that MongoDB was unable to be connected to (despite the MongoDB server is running). If the error persists over subsequent requests, then the app pool has to be recycled (or if IIS Express is being used, close the project solution and reopen it). There’s a similar bug report that has been open for the past couple of years so it appears to be something to grit and bear.