Mongo DB and .NET

This is my last blog post of the year 2017 where I am going to showcase how you can make the .NET application talk to a Mongo DB.

Just a quick recap…MongoDB is a document database that stores data in flexible, JSON-like documents, meaning fields can vary from document to document and data structures can be changed over time.

If you want to know about Mongo DB, what it is and why you should use it, you can read the article from one of my earlier posts here.

First things first, install the following:

  • Robo 3T from www.robomongo.org

Robo 3T (formerly Robomongo) is the free lightweight GUI embedded shell for MongoDB users.

Launch Visual Studio and create a Console App (.NET Framework).

Now install the following packages from NuGet:

  • MongoDB.Bson
  • MongoDB.Driver
  • MongoDB.Driver.Core

Packages

It’s time to write some code, but before that, add references to the project and use the following namespaces:

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
using System;
using System.Linq;

Let’s create a POCO class and call it Book. This is done in order for the document model to map to the objects in the application code therefore making data easy to work with.

    public class Book
    {
        public  ObjectId Id { get; set; }
        public string ISBN { get; set; }
        public string Title { get; set; }
        public string Author { get; set; }
        public DateTime Published { get; set; }
        public string Publisher { get; set; }
    }

Let’s insert a record into the book collection like so:

private static void InsertBook()
        {
            var client = new MongoDB.Driver.MongoClient();
            var db = client.GetDatabase("admin");
            var col = db.GetCollection("Books");

            Book objBook = new Book();
            objBook.Id = ObjectId.GenerateNewId();
            objBook.ISBN = "593220";
            objBook.Title = "Debgging Mongo App";
            objBook.Author = "Obi Oberoi, Ken Cenerelli";
            objBook.Published = Convert.ToDateTime("2017-12-31T00:00:00Z");
            objBook.Publisher = "Wrox";

            col.InsertOne(objBook);
        }

To get a book collection, use the code below:

private static void GetAllBooks()
        {
            var client = new MongoDB.Driver.MongoClient();
            var db = client.GetDatabase("admin");
            var col = db.GetCollection("Books");

            foreach(Book doc in col.Find(b=> b.Title.Length > 0)
                    .SortByDescending(b=> b.Title)
                    .ToList())
            {                
                Console.WriteLine("BookID: {0}", doc.Id);
                Console.WriteLine("Title: {0}", doc.Title);
                Console.WriteLine("Author: {0}", doc.Author);
            }
            Console.ReadLine();
        }

Let’s take our code to test by calling the methods from the Main program:

static void Main(string[] args)
        {         
            InsertBook();
            GetAllBooks();            
        }

As you saw in just a few lines of code, one could easily perform CRUD operations against MongoDB with a CLR compliant language such as C#.

About Obi Oberoi

Obi Oberoi is a Microsoft MVP (Visual Studio & Development Technologies), developer and a life-long student of continuous learning. Obi enjoys to code, read, and hang out with techies and geeks!
This entry was posted in NoSQL. Bookmark the permalink.