SIGN UP MEMBER LOGIN:    
ARTICLE

Mongo database with Query in C# .Net

Posted by Shirsendu Nandi Articles | ADO.NET in C# April 14, 2011
In this article I will describe the overview of a mongo database and it's query.
Reader Level:

Mongo database with query in C# .Net.

Content:

  • What is mongo Database
  • Language support for Mongo db .
  • Why we will use Mongo DB?
  • Data Model Hierarchy of Mongo Database
  • How to connect the Mongo db In your C# .NET Application
  • Insert single and multiple documents using C#
  • Fetching data from Mongo Db
  • Delete the database and the collection
  • What is mongo Database?
  • Mongo DB is an open source, high-performance, schema-free, document oriented database.
  • It has been written in C++ for the document-oriented database, so it manages collections of JSON-like documents.
  • Languages support Mongo db?
  • C
  • C++
  • Haskell
  • Java
  • Javascript
  • Perl
  • PHP
  • Python
  • Ruby
  • C#

 

Why we will use Mongo DB?

a. Document oriented (Documents (objects) map nicely to programming language data types and also no joins and no multi-document transactions for high performance and easy scalability)

b. High Performance (Indexes including indexing of keys from embedded documents and arrays, asynchronous write)

c. High Availability (If master server fails then it will automatically replicate the server)

Data Model Hierarchy of Mongo Database:

  • A Mongo system holds a set of databases (For e.g. Databases in SQL Server)

  • A database holds a set of collections

  • A collection holds a set of documents (tables in SQL Server)

  • A document is a set of fields (for e.g. attributes in tables)

  • A field is a key-value pair

  • A key is a name (string)

  • A value is a basic type like string, integer, float, timestamp, binary or a document, or an array of values (For e.g. Datatype in SQL Server).

        

How to connect the Mongo db In your c# .NET Application

First we have to use the namespaces shown below for accessing the mongo database with C# drive:

using MongoDB.Driver;

using MongoDB.Driver.Bson;

Now to connect to the Database:

var mongo = new Mongo();

            mongo.Connect();

            var db = mongo.getDB("testmongo"); 

 

Here we are creating the object variable of "mongo" database. Then we are going to open the connection of the database by writing "mongo.Connect();". It is like "con.open()" in ADO.Net programming. 

"mongo.getDB("testmongo");" means it will create the database name "testmongo" under the "c:\Data\db" folder.

Insert single and multiple Documents Using c#

For single document insert

 var mongo = new Mongo();

            mongo.Connect();

            var db = mongo.getDB("testmongo");

            var categorylist = db.GetCollection("studcategories");

            var category = new Document();

            category["Name"] = "shirsendu nandi";

            category["Id"] = "20";

            category["Adress"] = "bangalore";

            categorylist.Insert(category);

            Console.WriteLine("Total number of data is:-" + categorylist.Count());

For multiple Document(document under Document) insertion

var categories = northwind.GetCollection("Employeedetails");

            var category = new Document() { { "Title", "shirsendu nandi" } };

            category["Id"] = "11541";

            var Locations = new List<Document>() //add the multiple documents

                                {

                                    new Document() {{"Title", "Anoop"}},

                                    new Document() {{"Title", "Dipti"}},

                                    new Document() {{"Title", "sachin"}}

                                };

            category.Add("Locations", Locations.ToArray());//add the products in to the category

            // persist the category along with products 

            categories.Insert(category);//insert the Parent and the child documents uner the collection

Fetching Data from Mongo Db

Fetching all the collection Data by Find All Method

 var list = northwind.GetCollection("Employeedetails").FindAll().Documents;

 foreach (var lt in list)//to display the parent document

            {

                Console.WriteLine(lt["Title"]);

                Console.WriteLine(lt["Id"]);

            }

Fetching a particulat data from the Child Document by using  findone method

var persistedCategory = categories.FindOne(new Document() { { "Title", "shirsendu nandi" } });

 Console.WriteLine(persistedCategory["Title"]);

 foreach (var Location in (persistedCategory["Locations"] as Document[]))

            {

               Console.WriteLine(Location["Title"]);//display the child documents

}

Delete the Database and the collection from the Mongo Database

public void delete()

        {

         

            using (var mongo1 = new Mongo())

            {

                mongo1.Connect();

                var db = mongo1.getDB("Employee");

                db.MetaData.DropDatabase();

                Console.ReadLine();

            }

        }

 

Login to add your contents and source code to this article
share this article :
post comment
 
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
Team Foundation Server Hosting
Become a Sponsor