Thursday, July 17, 2014

NoSQL - MongoDB; Setup and Saving Data

Intro

In the previous post in this series I covered the basics of NoSQL data stores. I briefly mentioned MongoDB and its home in the NoSQL world as a document store. This week I'll go over some of the basics of using MongoDB in your c# code. Hold onto yer hats folks, we're in for a ride!

Setting up Mongo Locally

Go to the MongoDB download page, download and setup the correct version of Mongo for your OS. The instructions on their site are better than anything I can write, so do what they say and you'll be fine :). Be sure to actually run the MongoDB system after you install it (there are instructions for running the program on their website too), as it's pretty tough to connect to a database that isn't running.

A Free MongoDB GUI

MongoDB does not come with a GUI. If you've got a SQL Server background you've probably become accustomed to visualizing your data using SQL Server Management Studio, as it's a very handy GUI for navigating around your data. Mongo does have a couple options, they just don't come with MongoDB. For this tutorial, I'll be using MongoVue, which I suggest you download too for your own usage. I won't get into general usage of this program as it's pretty easy and it's detailed nicely on their website.

A Quick Bit of Mongo Terminology

If you have a SQL background you're well on your way to understanding how a MongoDB server is organized. The only thing that may throw you off initially is Mongo doesn't use tables. The closes thing they have is a Collection, which is roughly akin to a table. You're supposed to store only a single type of object within each collection, though it's not enforced. Still, it's a good idea as it keeps your data organized.

Saving Data

OK then cool cats, it's time to fire up Visual Studio and play with Mongo. Create yourself a new webforms project. I called mine BlogMongo, but call yours whatever you like. Now go into NuGet package manager and install the package "mongocsharpdriver" into your project. This NuGet package contains everything you need to read and write data using MongoDB and C#. It's the official package listed on the MongoDB site, so it's my preferred option though there are others out there.

Drop a server-side button on your webform.Call the button btnSave. Add a click() event to it.Add a couple using statements too; one for MongoDB.Bson and one for MongoDB.Driver. Now I'll work a little coding magic, paste it in here, and discuss below:

using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;

namespace BlogMongo
{
    public class Stuff
    {
        public Guid Id { get; set; }
        public int SomeInt { get; set; }
        public string SomeString { get; set; }
        public IList<string> ListOfStrings { get; set; }
        public Stuff()
        {
            ListOfStrings = new List<string>();
        }
    }

    public partial class Default : System.Web.UI.Page
    {
        private Stuff GenerateStuff()
        {
            var stuff = new Stuff() { Id = Guid.NewGuid(), SomeInt = new Random().Next(0, 10), SomeString = "yeah, a string" };
            for (int i = 0; i < stuff.SomeInt; i++)
                stuff.ListOfStrings.Add(i.ToString());
            return stuff;
        }

        private MongoCollection GetMongoCollection()
        {
            var client = new MongoClient("mongodb://localhost");
            var server = client.GetServer();
            var database = server.GetDatabase("BlogMongo");
            return database.GetCollection<Stuff>("stuffses");
        }

        private void SaveStuff()
        {
            var stuff = GenerateStuff();
            var collection = GetMongoCollection();
            collection.Save(stuff);
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            SaveStuff();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
        }
    }
}



You'll see after the using statements, the first thing we've done is add a class called Stuff. This is just our POCO (plain old CLR object) that we'll store in the database. The GenerateStuff() method within our page merely creates an object of type Stuff and puts some data in it.

GetMongoCollection() is where things start to get interesting. The first line in the function gets us a reference to an MongoClient object, which is how you connect to a Mongo database. The code is connecting to the local installation we did up above. Line 2 of the method gets a reference to the Mongo server. In this case it's the same machine, but hey we need an object. Line 3 gets a reference to a database named BlogMongo within the Mongo server. Those of you reading carefully might be thinking "uh...Pete, forget something? Like maybe creating the database?". Nay friends, nay! I forgot no such thing! Call it a feature or call it a piece of kryptonite, but Mongo will create a database automatically the first time you save some data into it. So, even though this database doesn't yet exist, we can reference it. Neato! Line 4 retrieves from the database a collection (or table if you'd rather) named stuffses. Note that this collection doesn't exist yet either; the same rule for database creation applies to collection creation.

The next interesting method is SaveStuff(). It's pretty compact at 3 lines, and the 3rd line is the only really new bit of awesome. This uses our collection reference that we created above and calls its Save() method in order to save our stuff object which is of type Stuff. The Save() method is used for an upsert. There are separate Insert() and Update() methods, but I prefer to use this multipurpose method.

Now, just to prove the magic is still alive in my relationship with the code, I ran this little fella and clicked the button 4 times. Here is the representation of our data in MongoVUE:


A quick note on the storage behind MongoDB: MongoDB stores its data in BSON format, which is Binary JSON. It's just a flavor of JSON with a little bit of extra bells and whistles. That's why, in the above screenshot of MongoVue, I elected to show you the JSON representation of our stored objects. JSON is a pretty universal communication mechanism these days, so getting used to seeing it an using it can only benefit you.

Ok one last quick note, then I'm done noting. Really: See how there is no field named Id in my stored objects in that MongoVue screenshot, even though there is a field in the class Stuff named Id? This is because the Mongo C# driver will automatically use any field named Id as your primary key/id field, which is how documents are identified within the MongoDB database. MongoDB however stores such fields with a name of _id unless you specify otherwise, so in this case the field Id (which is a useful standard, so name your Id fields this if you can) maps to _id in the MongoDB database.

What's Next?

Next week will be the final installment of NoSQL/Mongo. I'll show you guys how to query data. Maybe a few other tricks too if I have the time and we have enough space on the blog post.

I encourage you to read up on using the Mongo C# driver using the link in the resources section below.We only scratched the surface this week, and we'll lightly gouge it next week. There's still plenty we won't have time for though, so if you like MongoDB and you want to learn more, their website is the best place to get into it.

Resources

MongoDB-Getting Started With the C# Driver

No comments:

Post a Comment