Getting Started MongoDB With C#

Introduction

This article explains how to get started working with MongoDB using C#. This article will help you learn connecting to a server, creating a database, creating a collection, inserting a document into a collection, removing a document (data) from a collection, querying from a collection and so on. To work with MongoDB you need to download the MongoDB C# driver that supports MongoDB.

Working with MongoDB is the same as working in LINQ and Entity Framework. MongoDB contains the same features and the same work style that LINQ has. This is one of the great features of MongoDB.

Driver Line: https://github.com/mongodb/mongo-csharp-driver/releases

Getting Startded

Before coding, first download the driver, then add the reference of the two DLLs named MogoDB BOSON and MongoDbdriver and use the references of the following namespaces.

  1. using MongoDB.Bson;  
  2. using MongoDB.Driver;  
  3. using MongoDB.Driver.Builders;  
  4. using MongoDB.Driver.GridFS;  
  5. using MongoDB.Driver.Linq;  
Connection String Syntax

Default Connection String: "mongodb://localhost"

The preceding connection string will connect to the local default server having port 27017, you can use a customized connection like "mongodb://192.162.1.xx:27017".

Creating Client
  1. MongoClient client = new MongoClient(connectionString);  
Like a SQL connection you are required you create a MongoDB client, the code above creates an object of Mongoclient that takes a connection string as a parameter.

Getting Server Reference
  1. MongoClient client = new MongoClient(connectionString);  
  2. MongoServer server = client.GetServer();  
The code above gets a reference of Mongo server, it calls the GetServer() function of the Mongo client that returns objects of the Mongo server.

Getting Database Reference

To create a Mongo database to get a collection (table in SQL Server), where you store your data:
  1. MongoClient client = new MongoClient(connectionString);  
  2. MongoServer server = client.GetServer();  
  3. MongoDatabase database = server.GetDatabase("Test");  
This code calls the GetDatabase function to get a reference of the Mongo databse. The Get Database function takes the name of the server as a parameter. If the database is not available then MongoDB creates a database with a specified name in the parameter and returns the database. Here the code is trying to get a reference of the test database.

Getting Reference of Collection

Like SQL Server, a MongoDB database contains a collection to store data. To get a reference of the collection, it is required to call the get collection function of the MongoDB database.
  1. MongoClient client = new MongoClient(connectionString);  
  2. MongoServer server = client.GetServer();  
  3. MongoDatabase database = server.GetDatabase("Test");  
  4. MongoCollection symbolcollection= database.GetCollection<Symbol>("Symbols");  
The getcollection function takes a symbol name as parameter and returns a reference of the collection. Like the Get Database function, the Get Collection function also creates a collection. If a collection is not available then the specified name is the parameter. Here the symbol is an entity that specifies the type of collection.

Getting Reference of Collection List

A list of a Mongo collection can also be obtained by calling the GetCollections function of the database, it returns all the collections available in the database in a list.
  1. MongoClient client = new MongoClient(connectionString);  
  2. MongoServer server = client.GetServer();  
  3. MongoDatabase database = server.GetDatabase("Test");  
  4. List<MongoCollection> collections=database.GetCollections();  
Drop Collection from Database
  1. MongoClient client = new MongoClient(connectionString);  
  2. MongoServer server = client.GetServer();  
  3. MongoDatabase database = server.GetDatabase("Test");  
  4. database.DropCollection("Symbols");  
The Drop Collection function of the Mongo database class deletes a collection specified by the name in the parameter from the database.

Insert into Collection
  1. MongoClient client = new MongoClient(connectionString);  
  2. MongoServer server = client.GetServer();  
  3. MongoDatabase database = server.GetDatabase("Test");  
  4. MongoCollection symbolcollection= database.GetCollection<Symbol>("Symbols");  

  5. Symbol symbol = new Symbol ();  
  6. symbol.Name = “Star”;  
  7. symbolcollection.Insert(symbol);  
Symbol is a class, the code above inserts an object of a symbol into the collection. In the following you would have noticed id which is of type ObjectID. Property id is not specified in the code above because this is optional, if you do not specify a MongoDB collection then, like a SQL table, it automatically gives an id number to it. Like an auto-generated id column in a SQL Server table.
  1. public class Symbol  
  2. {  
  3. public string Name { getset; }  
  4. public ObjectId ID { getset; }  
  5. }  
Querying form Collection

Querig list of data

  1. MongoCollection symbolcollection= database.GetCollection<Symbol>("Symbols")  
  2. List< Symbol > query = symbolcollection.AsQueryable<Symbol>().Where<Entity>(sb => sb.Name == "Star").ToList();  
Same as queryig a sigle data
  1. Symbol symbol = symbolcollection.AsQueryable<Entity>().Where<Entity>(sb => sb.Name == "Kailash").SingleOrDefault();  
Saving Data into Collection
  1. MongoCollection symbolcollection= database.GetCollection<Symbol>("Symbols")  
  2. Symbol symbol = symbolcollection.AsQueryable<Entity>().Where<Entity>(sb => sb.Name == "Kailash").SingleOrDefault();  
  3. symbolcollection.Save(symbol);  
The save function of MongoDB collection saves an existing document.

For example, suppose you want to modify all the columns of an existing table and save the changes; then you need to get the help of the save function.

Updating Data

An alternative to Save is Update. The difference is that Save sends the entire document back to the server, but Update sends just the changes. The Update function takes a parameter.

For example: suppose you need to change some columns of a table and send only the updated column value to the server, in that case you need to use the Update function of the MongoDB collection.
  1. MongoCollection symbolcollection= database.GetCollection<Symbol>("Symbols")  
  2. var query3 = Query<Symbol>.EQ(e => e.Id, ("0000000000021325640.0");  
  3. var update = Update<Symbol>.Set(e => e.Name, "abc"); // update modifiers  
  4. symbolcollection.Update(query3, update);  
Removing Data From Collection

To remove an existing documet from the collection the Remove fuction helps. The Remove function takes an object of an entity as a parameter.
  1. MongoCollection symbolcollection= database.GetCollection<Symbol>("Symbols")  
  2. var query2 = Query< Symbol >.EQ(fd=>fd.Id, new ObjectId("0000000000021325640.0"));  
  3. symbolcollection.Remove(query2);  
To remove all the data from collection:
  1. symbolcollection.RemoveAll();  
Full Code
  1. using System;   
  2. using System.Collections.Generic;   
  3. using System.Linq;   
  4. using System.Text;   
  5. using System.Timers;   
  6. using MongoDB.Bson;   
  7. using MongoDB.Driver;   
  8. using MongoDB.Driver.Builders;   
  9. using MongoDB.Driver.GridFS;   
  10. using MongoDB.Driver.Linq;   
  11. using System.Data.SqlClient;   
  12. namespace MongodbRND   
  13. {   
  14.    class Program   
  15.    {   
  16.       static void Main(string[] args)   
  17.       {   
  18.          Console.WriteLine("Mongo DB Test Application");   
  19.          Console.WriteLine("====================================================");   
  20.          Console.WriteLine("Started By:Kailash Chandra Behera");   
  21.          Console.WriteLine("Started On: 14 July 2014");   
  22.          Console.WriteLine("Configuration Setting: 172.16.1.24:27017");   
  23.          Console.WriteLine("====================================================");   
  24.          Console.WriteLine("Initializaing connection");   
  25.          string connectionString = "mongodb://172.16.1.24:27017";   
  26.   
  27.   
  28.          Console.WriteLine("Creating Client..........");   
  29.          MongoClient client = null;   
  30.          try   
  31.          {   
  32.             client = new MongoClient(connectionString);   
  33.             Console.WriteLine("Client Created Successfuly........");   
  34.             Console.WriteLine("Client: " + client.ToString());   
  35.          }   
  36.          catch (Exception ex)   
  37.          {   
  38.             Console.WriteLine("Filed to Create Client.......");   
  39.             Console.WriteLine(ex.Message);   
  40.          }   
  41.   
  42.          Console.WriteLine("Initianting Mongo Db Server.......");   
  43.          MongoServer server = null;   
  44.          try   
  45.          {   
  46.             Console.WriteLine("Getting Servicer object......");   
  47.             server = client.GetServer();   
  48.   
  49.             Console.WriteLine("Server object created Successfully....");   
  50.             Console.WriteLine("Server :" + server.ToString());   
  51.          }   
  52.          catch (Exception ex)   
  53.          {   
  54.             Console.WriteLine("Filed to getting Server Details");   
  55.             Console.WriteLine(ex.Message);   
  56.          }   
  57.   
  58.   
  59.          Console.WriteLine("Initianting Mongo Databaser.........");   
  60.          MongoDatabase database = null;   
  61.          try   
  62.          {   
  63.             Console.WriteLine("Getting reference of database.......");   
  64.             database = server.GetDatabase("Kailash");   
  65.             Console.WriteLine("Database Name : " + database.Name);   
  66.          }   
  67.          catch (Exception ex)   
  68.          {   
  69.             Console.WriteLine("Failed to Get reference of Database");   
  70.             Console.WriteLine("Error :" + ex.Message);   
  71.          }   
  72.          try   
  73.          {   
  74.             Console.WriteLine("Deleteing Collection Symbol");   
  75.             database.DropCollection("Symbol");   
  76.          }   
  77.          catch (Exception ex)   
  78.          {   
  79.             Console.WriteLine("Failed to delete collection from Database");   
  80.             Console.WriteLine("Error :" + ex.Message);   
  81.          }   
  82.   
  83.          Console.WriteLine("Getting Collections from database Database.......");   
  84.   
  85.   
  86.          MongoCollection symbolcollection = null;   
  87.          try   
  88.          {   
  89.             symbolcollection = database.GetCollection<Symbol>("Symbols");   
  90.             Console.WriteLine(symbolcollection.Count().ToString());   
  91.          }   
  92.          catch (Exception ex)   
  93.          {   
  94.             Console.WriteLine("Failed to Get collection from Database");   
  95.             Console.WriteLine("Error :" + ex.Message);   
  96.          }   
  97.          ObjectId id = new ObjectId();   
  98.          Console.WriteLine("Inserting document to collection............");   
  99.          try   
  100.          {   
  101.             Symbol symbol = new Symbol ();   
  102.             symbol.Name = “Star”;   
  103.             symbolcollection.Insert(symbol);   
  104.             id = symbol.ID;   
  105.   
  106.             Symbol symbol = new Symbol ();   
  107.             symbol.Name = “Star1”;   
  108.             symbolcollection.Insert(symbol);   
  109.             id = symbol.ID;   
  110.   
  111.             Console.WriteLine(symbolcollection.Count().ToString());   
  112.          }   
  113.          catch (Exception ex)   
  114.          {   
  115.             Console.WriteLine("Failed to insert into collection of Database " + database.Name);   
  116.             Console.WriteLine("Error :" + ex.Message);   
  117.          }   
  118.   
  119.          try   
  120.          {   
  121.             Console.WriteLine("Preparing Query Document............");   
  122.             List< Symbol > query = symbolcollection.AsQueryable<Entity>().Where<Entity>(sb => sb.Name == "Kailash").ToList();   
  123.   
  124.             Symbol symbol = symbolcollection.AsQueryable<Entity>().Where<Entity>(sb => sb. ID == id).ToList();   
  125.   
  126.          }   
  127.          catch (Exception ex)   
  128.          {   
  129.             Console.WriteLine("Failed to query from collection");   
  130.             Console.WriteLine("Exception :" + ex.Message);   
  131.          }   
  132.          Console.WriteLine("");   
  133.          Console.WriteLine("====================================================");   
  134.          Console.ReadLine();   
  135.       }   
  136.    }   
  137.    public class Symbol   
  138.    {   
  139.       public string Name { getset; }   
  140.       public ObjectId ID { getset; }   
  141.    }   
  142. }   
Summary

In this illustration we learned about MongoDB and how to work with MongoDB using C#. We learned connecting to a server, getting the database reference, creating a collection, inserting into a collection, querying from a collection and so on.

 

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now