Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

MongoDB Quickstart Tutorial in C# and Linqpad

0.00/5 (No votes)
8 May 2011 1  
MongoDB quickstart tutorial in C# and Linqpad

Introduction

MongoDB is a non-relational database for storing objects (or documents), it's a really nice alternative to the traditional database paradigm and allows the storage and serialization of C# classes and properties.

Here is my Quick Start Tutorial

If you don't already have a MongoDb installation, I recommend going for the hosted option at https://mongohq.com/home (free option available).

You then need to download the official 10gen C# driver: https://github.com/mongodb/mongo-csharp-driver/downloads.

Finally you should download Linqpad. I really love this app, you can use it as a C# scratchpad to rapidly mess about with any new libraries or code bases and is a great alternative to running a console app. Just edit your code and hit F5 to run the app. It's especially useful when you want to dump out objects structures to the screen visually, in this case MongoDB data. You can download LinqPad at http://www.linqpad.net/.

Super Quickstart

  1. https://mongohq.com/homeCreate a database here
  2. https://github.com/mongodb/mongo-csharp-driver/downloadsDownload the Driver
  3. http://www.linqpad.net/Download this badboy

Configuring Linqpad

There is a quick configuration element to Linqpad, we have to add the driver DLL reference and namespace:

First add the DLLs:

linqpad1.JPG

Now add the namespaces:

linqpad2.JPG

Mongolific! Now we are ready to rock and roll!

Here is a simple example to insert a document (an object class) into a table, and then retrieve it again using a simple query.

linqpad3.JPG

Here is the code for copy and paste land:

void Main()
{
	var server = MongoServer.Create("mongodb://law:pass@pearl.mongohq.com:27071/");

	var db = server.GetDatabase("Universe");

	var collection = db.GetCollection<Planet>("Planet");

	var pluto = new Planet()
	{
		Name = "Pluto",
		Colour = "Purple"

	};

	collection.Insert(pluto);

	var query = Query.And(Query.EQ("Name", "Pluto"));

	var list = collection.Find(query).ToList();

	list.Dump();
}

public class Planet
{
	public ObjectId  Id { get; set; }
	public string Name { get; set; }
	public string Colour { get; set; }
} 

Simples!

.NET silicon valley

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here