Internet Tutorials for c# programming, databases, web site development and performance tuning.

Using MongoDB with C# Examples

Using MongoDB with C# Examples

12 months ago by 6494de52-0d26-44fd-96e0-c41972d112c7

Using MongoDB with C# Examples MongoDB is an open source NoSQL solution that offers high availability, scabaility and high performance in a low footprint package. Mongodb is a fantastic tool for developers wanting to move into the world of NoSQL databases and offers a wide range of connectivity options for storing and reading data from mongoDB. This tutorial is aimed at showing c# developers how easy it is to migrate your data driven applications to MongoDB. If you are "traditional" SQL developer who is used to using Select, Insert and Update statements can see how easy it is to start writing code for MongoDB. MongoDB is a great a development tool as it speeds up the development process alowing you to focus more on key functions rather than worrying about database connectivity, authentication and query performance. As more and more of my projects migrate to MongoDB I am finding that much of my code is being re-used and some of this key code is shown below.

Before You Begin - Install MongoDB You will need to install MongoDB by following the guide on the MongoDB website. MongoDB supports high availabilty with Replication and High Scalability with Sharding however for the purposes of this tutorial I am going to assume you have a single locally available test instance. When you want to put applications into production its usually just a case of modifying your initial connection. Installing and Using The Driver MongoDB provides a REST interface for making queries and adding/update so there is nothing stopping you using HTTP to begin using MongoDB - however to make our lives easier 10gen the company that make MongoDB also provide a number of drivers for different programmign languages - you will need to install and reference the MongoDB c# driver in your projects to begin using the MongoDB code below. If you use Microsoft Visual Studio you can do this very easily using the wonderful NuGet tool (and if you havent heard of this before I urge you to do some research on this). Search for MongoDB and you will be able to install the MongoDB driver into your project in one click after accepting the license agreement.

One this is done you can simply adding a couple of using statements in your code to access the MongoDB objects.

using MongoDB.Bson;
using MongoDB.Driver;

Connecting to MongoDB

As with the majority of database servers you will initially need to make a connection to a server and then create/connect to a database. This might include some authentication paramaters but lets assume you are running a local MongoDB instance for testing. Note that with MongoDB the database will automatically be created for you if it doesnt exist.

MongoServer server = MongoServer.Create("");
MongoDatabase db = server.GetDatabase("MyDatabase");

We need to create a simple class to allow us to demonstrate working with MongoDB. Here is a simple class delaration that I will use for the rest of the tutorial.

MongoServer server = MongoServer.Create("");
MongoDatabase db = server.GetDatabase("MyDatabase");

Create some objects to work with, notice that our objects require an Object ID which requires the MongoDB.BSON namespace.

public class Car
 public ObjectId _id;
 public string CarDescription { get; set; }
 public string ManufacturerName { get; set; }
 public DateTime DateOfManufacture { get; set; }
 public int EngineSize { get; set; }

This code opens a collection. If the collection doesn't exist it will automatically be created. If you are coming from an SQL background - yes this means you dont have to worry about create table statements.

// this is out collection, similar to a table in SQL

MongoCollection cars = db.GetCollection("Cars");

Inserting Data

// save into our collection


// insert batch is most efficient way of inserting a lot of data
// use it in your application if you can

List mycars = new List();

Updating Data

//update our data where we can match using a query

var query = Query.EQ("CarDescription", "BMW M5");
var update = Update.Set("CarDescription", "BMW M5 V8")
    .Set("EngineSize", "4000");
cars.Update(query, update);

// alternative is to find then save

var query2 = Query.EQ("CarDescription", "BMW M5");

// this will ensure only one row is matches, otherwise you will get an exception

Car c = cars.FindOneAs(query2); 
c.CarDescription = "BMW M5 V8";

// you can also update if you know the document ID

var query3 = Query.EQ("_id", new ObjectId("4ff4a59129d81413a483f39c"));
var update3 = Update.Set("CarDescription", "BMW M5 V8")
    .Set("EngineSize", "4000");
cars.Update(query3, update3);

Deleting Data

// Simple delete using a query to match on Object ID

var deletequery = Query.EQ("_id", new ObjectId("4ff4a59129d81413a483f39c"));

Finding Data

// Get All Objects

var allCarResult = cars.FindAll();

foreach (Car car_item in allCarResult)
 // something here

// Find One Object

var FindByID = Query.EQ("_id", new ObjectId("4ff4a59129d81413a483f39c"));
Car carResult = cars.FindOneAs(FindByID);

// Find List of Matching Objects

var FindByManufacturer = Query.EQ("ManufacturerName", "BMW");
List carResults = cars.FindAs(FindByManufacturer).ToList();

// Find List of Matching Objects, with ordering example

var FindByManufacturerOrder = Query.EQ("ManufacturerName", "BMW");
List carListResults = cars.FindAs(FindByManufacturerOrder).OrderBy( cl => cl.CarDescription ).ToList();

Creating Indexes

Indexes are essential to ensure high performance querying for collections. You can create indexes programmatically by using the following code

// Simple delete using a query to match on Object ID

var deletequery = Query.EQ("_id", new ObjectId("4ff4a59129d81413a483f39c"));

This tutorial will be updated in the future with some Advanced Queries - please check back later.

I hope you enjoyed this brief introduction to using MongoDB with c#. As a seasoned SQL user I am always looking to find ways to improve performance of my applications and write more efficient code and MongoDB allows me to write cleaner code with better performing applications in less time. In conclusion if you have an application that doesnt require transactions and is flexible on its database options then MongoDB is definitely worth looking into. - See more at: