Craftsman at Work

I'm Artur Karbone, coding software architect and independent IT consultant and this is my blog about craftsmanship, architecture, distributed systems, management and much more.

My Experience with MongoDB University Part 1: The Beginning

Just signed up for "M101N: MongoDB for .NET Developers" course, offered by MongoDB University and going to share my experience in this series of blog posts. I want to do it via a set of katas or a set of short theses, if You will. It's just me learning MongoDB.

Kata #1. Install the beast

First of all download it from here.

The installation process is as simple as next, next, next.

Detailed instructions are available here.

Heads up. I suggest adding mongodb bin path (which is C:\Program Files\MongoDB\Server\3.2\bin in my machine) to the %PATH% variable, so You can run mongo commands from any place in Your console:

alt

Kata #2. Some theses
  • Non relational
  • Collections are analogous to tables in relational databases
  • Documents are analogus to records
  • JSON is way much closer to what you have inside your programs (I mean if you need to display a blog post with some comments, tags, etc. why not just treat that post as a single entity - not a set of tables)
  • JSON is a simple key/value (dictionary) structure
  • JSON might be hierarchical (can’t do that in relational db)
  • Schemaless = dynamic schema
  • Does not support joins/does not support SQL as a query language
  • No transactions, but since you save the whole document, in most of the cases it is not an issue (Remember, you don't insert/update authors/comments/blog/tags tables like in traditional relational db within a transaction. You rather update/insert the whole JSON document, which represents the blog entity. Which is an atomic operation anyway)
Kata #3. Start it off
  • mongod - is a server. Start it first.
  • mongo - console client.
  • mongos - used for sharding.

alt

Kata #4. The commands

You can do a lot of stuff from the console. Here is a reference with available commands. Let's look at just a few of them.

  • use [db name] - Connects to a database. Creates the database if it does not exist yet.

  • db.people.insert([some JSON]) or db.people.save([some JSON]) Inserts a document to a collection (named people in that particular case).

  • db.people.find() - Finds all documents in a collection.

  • db.people.find({FirstName:"John"}) -An analogue of the WHERE clause:
> db.people.find()
{ "_id" : ObjectId("568ec71be323cb21041e9520"), "FirstName" : "John", "LastName" : "Smith" }
{ "_id" : ObjectId("568ec71be323cb21041e9521"), "FirstName" : "Will", "LastName" : "Smith" }
> db.people.find({FirstName:"John"})
{ "_id" : ObjectId("568ec71be323cb21041e9520"), "FirstName" : "John", "LastName" : "Smith" }
> db.people.find({FirstName:"Joh1n"})
> db.people.find({FirstName:"John"})
{ "_id" : ObjectId("568ec71be323cb21041e9520"), "FirstName" : "John", "LastName" : "Smith" }
  • db.things.find.pretty() - Finds all documents in a collection and prettify the output:
> db.people.find().pretty()
{
        "_id" : ObjectId("568ec71be323cb21041e9520"),
        "FirstName" : "John",
        "LastName" : "Smith"
}
{
        "_id" : ObjectId("568ec71be323cb21041e9521"),
        "FirstName" : "Will",
        "LastName" : "Smith"
}
Kata #5. Writing some code

I went ahead and wrote a simple proof of concept app to see how .NET mongo driver works. Detailed querying information with .NET driver is available here.

Basically, the app just inserts two documents and retrieves them in two different ways - via Find and FindAsync. Here is a gist:

    class Program
    {
        public class Person
        {
            public ObjectId Id { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
        }

        public class MongoFirstConcept
        {
            public void InsertPeople()
            {
                var peopleCollection = GetPeopleCollection();

                peopleCollection.InsertOneAsync(new Person() { FirstName = "John", LastName = "Smith" });
                peopleCollection.InsertOneAsync(new Person() { FirstName = "Will", LastName = "Smith" });
            }

            public async void RetrievePeople1()
            {
                Console.WriteLine("RetrievePeople1");
                var people = await GetPeopleCollection().Find(_ => true).ToListAsync();
                foreach (var person in people)
                {
                    Console.WriteLine(person.FirstName);
                }
            }
            public async void RetrievePeople2()
            {
                Console.WriteLine("RetrievePeople2");
                using (var cursor = await GetPeopleCollection().FindAsync(_ => true))
                {
                    while (await cursor.MoveNextAsync())
                    {
                        var batch = cursor.Current;
                        foreach (var person in batch)
                        {
                            Console.WriteLine(person.FirstName);
                        }
                    }
                }
            }

            public void Run()
            {
                InsertPeople();
                RetrievePeople1();
                RetrievePeople2();
            }

            private IMongoCollection<Person> GetPeopleCollection()
            {
                MongoClient client = new MongoClient();
                var db = client.GetDatabase("test");
                return db.GetCollection<Person>("people");
            }
        }

        static void Main(string[] args)
        {
            new MongoFirstConcept().Run();
            Console.ReadLine();
        }
    }

Related Posts:

My Experience with MongoDB University Part 1: The Beginning

My Experience with MongoDB University Part 2: When Your Schema is changed

comments powered by Disqus