Mongo database with Query in C# .Net


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();

            }

        }

 


Similar Articles