MongoDB in .NET part 1: foundations

Introduction

There has been a strong increase in the usage of document based NoSql databases in the previous years. One prominent example is MongoDb. The default choice for storing data in a .NET project has most often been SQL Server. While SQL Server is probably still the most popular choice .NET developers can choose from other well-tested alternatives depending on their project needs. There is a whole suite of NoSQL databases out there besides MongoDb. Some examples:

At the time of writing this post MongoDb was the most popular NoSQL database according to db-engines. Even if you’re a staunch relational DBMS advocate and think you’ll never use anything else for your data storage solution it’s still beneficial to know that there are other tools out there. Also, you can have have a mixed data storage strategy where you store some objects in a relational DBMS and some others in a document store depending on the objects’ nature and the advantages and disadvantages of each storage mechanism.

You know that “we’ve always done it this way” is a dangerous mindset. Studying MongoDb can widen your skills set and offer a different point of view to solving data storage challenges.

In this series we’ll explore MongoDb in more details and how it can used in a .NET project.

MongoDb terms

As hinted at above MongoDb is a document-based database. In SQL Server the records are stored in rows where each column usually represents a property of the object that the table describes. In MongoDb however, information is stored in JSON documents – or to be exact, in Binary JSON, i.e. BSON. Here’s an example from the MongoDb homepage:

{
"_id": 1,
"name": {
"first": "John",
"last": "Backus"
},
"contribs": ["Fortran",
"ALGOL",
"Backus-Naur Form",
"FP"],
"awards": [{
"award": "W.W. McDowell Award",
"year": 1967,
"by": "IEEE Computer Society"
},
{
"award": "Draper Prize",
"year": 1993,
"by": "National Academy of Engineering"
}]
}

You’ll immediately notice that the properties such as “awards” can be arrays where each element in turn has their own properties. If you’re familiar with JSON then this is no surprise to you. As the documents are stored in binary format you cannot just open a BSON document in a text editor however.

The above JSON/BSON string is an example of a document. It consists of a set of key-value pairs such as _id = 1. Each key-value pair is an element or a field. You can see that “name” itself is a document within the larger document, also called an embedded document. A group of related documents is called a collection. A collection is similar to a table in SQL Server.

Each document has a unique ID field denoted by “_id”. It has the same function as a unique primary key in an SQL Server table. It can be of any type really but it’s customary to make it of type ObjectId which looks similar to a GUID. No matter which type you use, the ID must be unique across the collection of documents.

Advantages

There are some key advantages of MongoDb compared to traditional “table-based” databases:

  • Dynamic data structure with flexible schemas: you don’t need to define columns and tables. You can in fact store pretty much anything within the same collection
  • Due to the lack of strict schemas data migrations become a lot easier too: if you change your domain structure, i.e. you business objects in code, the document will store the objects correspondingly. You can force a change in the schema through changing your custom objects automatically
  • You don’t need separate tables to show relationships: the above JSON structure shows you that there’s no need for a separate “awards” collection, you can show the relationship directly within the document – there’s no need for foreign keys and constraints. If you extract a single item from a collection then you’ll immediately get its associated objects: order with all order items, rock band with all concerts, making it a breeze to perform operations on those linked objects
  • MongoDb documents therefore allow storing your objects in an object oriented fashion which is sometimes difficult and awkward to solve in SQL Server with separate tables and keys
  • Due to the lack of constraints such as secondary keys updating and deleting items will be easier: there’s no cascade delete, no orphans
  • Speed: MongoDb is very fast and efficient in querying and inserting items in a collection

Disadvantages

All of the above is very well and good but there are couple of things that you need to be aware of if you’re coming from an SQL Server environment – which probably at least 95% of .NET developers do.

  • Lack of professional tools: with SQL Server you can use SSMS for some very advanced GUI-based database operations, such as database profiling, SQL jobs, a query editor, IntelliSense and a whole lot more. There’s no equivalent in MongoDb. If you want to work directly with collections without one of the drivers – C#, Java, Php etc – then you’ll need to write your code in a console window or develop a custom solution yourself. There’s one visual tool though that you can use to improve the administration of your MongoDb database: RoboMongo
  • As of writing this post MongoDb doesn’t support transactions
  • Many developers will say that the lack of a schema is actually a disadvantage: you cannot associate objects through keys, you cannot force a compulsory data structure like “NOT NULL”
  • No stored procedures
  • Difficult to retrieve lost data

You can read more about the advantages and disadvantages of MongoDb here.

Drivers

While you can interact with MongoDb directly in a command window you’ll most certainly prefer to do that in code through a client library, a.k.a a driver. There are drivers available for most mainstream languages, like C#, Java or PHP. You can check out the full list of language-specific drivers here.

In the next post we’ll look at how to set up MongoDb and how to connect to it from code.

You can view all posts related to data storage on this blog here.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

4 Responses to MongoDB in .NET part 1: foundations

  1. Pingback: Lindermann's Blog | MongoDB Series

  2. Murari says:

    Can you please write an application which uses onion architecture using dependency injection, repository pattern, Asp.net MVC, Web Api, Poco Entities and View Models, Mongodb as database and Angular.js as Frontend framework. I’ve studied a lot but couldn’t find anything that comprises all of the above in one application. Thank you

    • Andras Nemes says:

      I don’t know anything about angular.js and I’m not planning to explore it anytime soon. JavaScript and its derivatives are just not my cup of tea. The current series I’m publishing on DDD has most of what you’ve mentioned: dependency injection, repo pattern, web api, poco, view models. It has EF/SQL Server as the backing store but I’m planning on adding MongoDb to it as well. However, an angular.js based front end is simply not on my radar.
      //Andras

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: