MongoDB CRUD Operations Using C#

In MongoDB articles series I discussed the basic concepts of MongoDB database. Today, I will explain how to perform MongoDB crud operation with C#.

Let’s start today’s session, first we learn how to connect MongoDB with ASP.NET and after that we perform MongoDB crud operation using C#.

Prerequisites

  • MongoDB
  • Visual Studio
  • MongoDB drivers for C#

We perform the MongoDB crud operation using ASP.NET website. So follow these Steps.

Step 1: Open Visual Studio.

Click on “New WebSite” and select an ASP.NET Empty Web Site.

Step 2: Now right click on Project Name and select “Manage NuGet Packages”.

newget package

Step 3: Now select Online option and download the following drivers.

select Online option

Now check the Bin folder you will find that the following libraries has been added.

Bin folder

Step 4: Add a new Web Form and provide the following name to the web from “MongoDB_Form” after that copy the following code into that Web from.

  1. <form id="form1" runat="server">  
  2.     <div>  
  3.         <div style="background-color:azure;width:100%; height:100px">  
  4.             <span style="margin-top:10px; margin-left:200px;font-size:40px;color:coral"> MongoDB CRUD Operations</span>  
  5.         </div>  
  6.   
  7.         <div style="margin-top:40px;margin-left:200px">  
  8.             <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" AutoGenerateColumns="False">  
  9.                 <AlternatingRowStyle BackColor="White" />  
  10.                 <Columns>  
  11.                     <asp:BoundField DataField="_id" HeaderText="ObjectID" SortExpression="Eval("_id")">  
  12.                         <ItemStyle Font-Size="X-Large" />  
  13.                     </asp:BoundField>  
  14.                     <asp:BoundField DataField="Student_ID" HeaderText="Student_ID" ReadOnly="True">  
  15.                         <ControlStyle BackColor="#6699FF" />  
  16.                         <ItemStyle Font-Size="X-Large" />  
  17.                     </asp:BoundField>  
  18.                     <asp:BoundField DataField="Name" HeaderText="Student_Name">  
  19.                         <ItemStyle Font-Size="X-Large" />  
  20.                     </asp:BoundField>  
  21.                     <asp:BoundField DataField="Class" HeaderText="Student_Class">  
  22.                         <ItemStyle Font-Size="X-Large" />  
  23.                     </asp:BoundField>  
  24.                     <asp:BoundField DataField="Subject" HeaderText="Student_Subject" SortExpression="Subject">  
  25.                         <ItemStyle Font-Size="X-Large" />  
  26.                     </asp:BoundField>  
  27.                     <asp:TemplateField>  
  28.                     </asp:TemplateField>  
  29.                 </Columns>  
  30.                 <EditRowStyle BackColor="#7C6F57" />  
  31.                 <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />  
  32.                 <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />  
  33.                 <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />  
  34.                 <RowStyle BackColor="#E3EAEB" />  
  35.                 <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />  
  36.                 <SortedAscendingCellStyle BackColor="#F8FAFA" />  
  37.                 <SortedAscendingHeaderStyle BackColor="#246B61" />  
  38.                 <SortedDescendingCellStyle BackColor="#D4DFE1" />  
  39.                 <SortedDescendingHeaderStyle BackColor="#15524A" />  
  40.             </asp:GridView>  
  41.         </div>  
  42.         <div style="background-color:blanchedalmond;width:100%; height:50px;margin-top:10px;text-align:justify">  
  43.             <span style="margin-top:10px; margin-left:200px;font-size:40px;color:chocolate">Select A Operation</span>  
  44.         </div>  
  45.         <div style="margin-top:30px">  
  46.   
  47.             <div runat="server" id="Save">  
  48.                 <table>  
  49.                     <tr>  
  50.                         <td style="padding-left:200px;font-size:25px">  
  51.                             <asp:Label runat="server" Text="ObjectID"></asp:Label>  
  52.                         </td>  
  53.                         <td style="padding-left:122px">  
  54.                             <asp:TextBox runat="server" width="400px" Height="25px" ID="txtObjectID"></asp:TextBox>  
  55.                         </td>  
  56.                         <td style="padding-left:200px">  
  57.                             <asp:Button runat="server" Text="Submit" Height="35px" Width="100px" BackColor="WindowFrame" Font-Bold="true" ID="Button1" OnClick="Submit"></asp:Button>  
  58.                         </td>  
  59.                     </tr>  
  60.   
  61.                 </table>  
  62.             </div>  
  63.   
  64.             <table>  
  65.                 <tr>  
  66.                     <td style="padding-left:200px;font-size:25px">  
  67.                         <asp:Label runat="server" Text="Student_ID"></asp:Label>  
  68.                     </td>  
  69.                     <td style="padding-left:50px">  
  70.                         <asp:TextBox runat="server" width="400px" Height="25px" ID="txtStudentID"></asp:TextBox>  
  71.                     </td>  
  72.                     <td style="padding-left:200px">  
  73.                         <asp:Button runat="server" Text="Insert" Height="35px" Width="100px" BackColor="Green" Font-Bold="true" ID="Insert" OnClick="Insert_Record"></asp:Button>  
  74.                     </td>  
  75.                 </tr>  
  76.                 <tr>  
  77.                     <td style="padding-left:200px;font-size:25px">  
  78.                         <asp:Label runat="server" Text="Student_Name"></asp:Label>  
  79.                     </td>  
  80.                     <td style="padding-left:50px">  
  81.                         <asp:TextBox runat="server" width="400px" Height="25px" ID="txtStudentName"></asp:TextBox>  
  82.                     </td>  
  83.                     <td style="padding-left:200px;">  
  84.                         <asp:Button runat="server" Text="Update" Height="35px" Width="100px" BackColor="Teal" Font-Bold="true" OnClick="Update_Record"></asp:Button>  
  85.                     </td>  
  86.                 </tr>  
  87.                 <tr>  
  88.                     <td style="padding-left:200px;font-size:25px">  
  89.                         <asp:Label runat="server" Text="Student_Class"></asp:Label>  
  90.                     </td>  
  91.                     <td style="padding-left:50px">  
  92.                         <asp:TextBox runat="server" width="400px" Height="25px" ID="txtStudentClass"></asp:TextBox>  
  93.                     </td>  
  94.                     <td style="padding-left:200px">  
  95.                         <asp:Button runat="server" Text="Save" Height="35px" Width="100px" BackColor="Thistle" Font-Bold="true" OnClick="Save_Record"></asp:Button>  
  96.                     </td>  
  97.                 </tr>  
  98.                 <tr>  
  99.                     <td style="padding-left:200px;font-size:25px">  
  100.                         <asp:Label runat="server" Text="Student_Subject"></asp:Label>  
  101.                     </td>  
  102.                     <td style="padding-left:50px">  
  103.                         <asp:TextBox runat="server" width="400px" Height="25px" ID="txtStudentSubject"></asp:TextBox>  
  104.                     </td>  
  105.                     <td style="padding-left:200px">  
  106.                         <asp:Button runat="server" Text="Delete" Height="35px" Width="100px" BackColor="Red" Font-Bold="true" OnClick="Delete_Record"></asp:Button>  
  107.                     </td>  
  108.                 </tr>  
  109.             </table>  
  110.         </div>  
  111. </form>  
Now add the following code in MongoDB_Form.aspx.cs file.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using MongoDB.Driver;  
  8. using MongoDB.Bson;  
  9. using System.Data;  
  10. using System.Configuration;  
  11.   
  12. namespace WebApplication1 {  
  13.     public partial class MongoDBForm: System.Web.UI.Page {  
  14.         MongoDB_Class _Obj = MongoDB_Class.GetObject();  
  15.         Student_Info StuObj_;  
  16.         protected void Page_Load(object sender, EventArgs e) {  
  17.             if (!IsPostBack) {  
  18.                 Page.FindControl("Save").Visible = false;  
  19.                 Load_Data();  
  20.             }  
  21.         }  
  22.   
  23.         public void Load_Data() {  
  24.             try {  
  25.   
  26.                 List < Student_Info > Student_List = new List < Student_Info > ();  
  27.                 Student_List = _Obj.Retrieve_Student_Information();  
  28.                 GridView1.DataSource = Student_List;  
  29.                 GridView1.DataBind();  
  30.             } catch (Exception Exp) {  
  31.                 Response.Write(Exp.Message);  
  32.             }  
  33.   
  34.         }  
  35.   
  36.   
  37.   
  38.         protected void Insert_Record(object sender, EventArgs e) {  
  39.             try {  
  40.   
  41.                 StuObj_ = new Student_Info();  
  42.                 StuObj_.Student_ID = int.Parse(txtStudentID.Text.ToString().Trim());  
  43.                 StuObj_.Name = txtStudentName.Text.ToString().Trim();  
  44.                 StuObj_.Class = int.Parse(txtStudentClass.Text.ToString().Trim());  
  45.                 StuObj_.Subject = txtStudentSubject.Text.ToString().Trim();  
  46.                 _Obj.Insert_Student_Information(StuObj_);  
  47.                 Load_Data();  
  48.             } catch (Exception Exp) {  
  49.                 Response.Write(Exp.Message);  
  50.             }  
  51.         }  
  52.   
  53.         protected void Update_Record(object sender, EventArgs e) {  
  54.             StuObj_ = new Student_Info();  
  55.             StuObj_.Student_ID = int.Parse(txtStudentID.Text.ToString().Trim());  
  56.             StuObj_.Name = txtStudentName.Text.ToString().Trim();  
  57.             StuObj_.Class = int.Parse(txtStudentClass.Text.ToString().Trim());  
  58.             StuObj_.Subject = txtStudentSubject.Text.ToString().Trim();  
  59.             _Obj.Update_Student_Information(StuObj_);  
  60.             Load_Data();  
  61.         }  
  62.   
  63.         protected void Save_Record(object sender, EventArgs e) {  
  64.             Page.FindControl("Save").Visible = true;  
  65.   
  66.         }  
  67.   
  68.   
  69.   
  70.         protected void Delete_Record(object sender, EventArgs e) {  
  71.   
  72.             StuObj_ = new Student_Info();  
  73.             StuObj_.Student_ID = int.Parse(txtStudentID.Text.ToString().Trim());  
  74.             _Obj.Delete_Student_Infromation(StuObj_);  
  75.             Load_Data();  
  76.         }  
  77.   
  78.         protected void Submit(object sender, EventArgs e) {  
  79.             StuObj_ = new Student_Info();  
  80.             StuObj_._id = ObjectId.Parse(txtObjectID.Text.ToString().Trim());  
  81.             StuObj_.Student_ID = int.Parse(txtStudentID.Text.ToString().Trim());  
  82.             StuObj_.Name = txtStudentName.Text.ToString().Trim();  
  83.             StuObj_.Class = int.Parse(txtStudentClass.Text.ToString().Trim());  
  84.             StuObj_.Subject = txtStudentSubject.Text.ToString().Trim();  
  85.             _Obj.Save_Student_Information(StuObj_);  
  86.             Load_Data();  
  87.             Page.FindControl("Save").Visible = false;  
  88.         }  
  89.   
  90.   
  91.   
  92.   
  93.     }  
  94. }  
Step 5: Now we add a class and write all the CRUD operations for MongoDB in this class.

So add a class and provide MongoDB_Class” name to that class after that copy the following code into this class.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using MongoDB.Driver;  
  8. using MongoDB.Bson;  
  9. using System.Data;  
  10. using MongoDB.Shared;  
  11. using MongoDB.Driver.Builders;  
  12. using MongoDB.Bson.Serialization;  
  13.   
  14. /// <summary>  
  15. /// Summary description for MongoDB_Class  
  16. /// </summary>  
  17. public class Student_Info {  
  18.     public ObjectId _id {  
  19.         get;  
  20.         set;  
  21.     }  
  22.   
  23.     public Int32 Student_ID {  
  24.         get;  
  25.         set;  
  26.     }  
  27.     public String Name {  
  28.         get;  
  29.         set;  
  30.     }  
  31.     public int Class {  
  32.         get;  
  33.         set;  
  34.     }  
  35.     public String Subject {  
  36.         get;  
  37.         set;  
  38.     }  
  39. }  
  40. public class MongoDB_Class {  
  41.     MongoServerSettings Settings_;  
  42.     MongoServer server;  
  43.     MongoDatabase Database_;  
  44.     public static MongoDB_Class _Obj;  
  45.     public static MongoDB_Class GetObject() {  
  46.         if (_Obj == null) {  
  47.             _Obj = new MongoDB_Class();  
  48.         }  
  49.   
  50.         return _Obj;  
  51.     }  
  52.   
  53.     public MongoDB_Class() {  
  54.         Settings_ = new MongoServerSettings();  
  55.         Settings_.Server = new MongoServerAddress("localhost", 27017);  
  56.         server = new MongoServer(Settings_);  
  57.         Database_ = server.GetDatabase("Temp");  
  58.   
  59.   
  60.     }  
  61.   
  62.     public List < Student_Info > Retrieve_Student_Information() {  
  63.         try {  
  64.             server.Connect();  
  65.             List < Student_Info > Student_List = new List < Student_Info > ();  
  66.             var StuInfo = Database_.GetCollection < Student_Info > ("Student_Information");  
  67.   
  68.             foreach(Student_Info Stu in StuInfo.FindAll()) {  
  69.                 Student_List.Add(Stu);  
  70.             }  
  71.   
  72.             return Student_List;  
  73.         } catch {  
  74.             throw;  
  75.         } finally {  
  76.             server.Disconnect();  
  77.         }  
  78.     }  
  79.   
  80.     public void Insert_Student_Information(Student_Info _Obj) {  
  81.         try {  
  82.             server.Connect();  
  83.             MongoCollection < Student_Info > Collection_ = Database_.GetCollection < Student_Info > ("Student_Information");  
  84.             BsonDocument Stu_Doc = new BsonDocument {  
  85.                 {  
  86.                     "Student_ID", _Obj.Student_ID  
  87.                 }, {  
  88.                     "Name", _Obj.Name  
  89.                 }, {  
  90.                     "Class", _Obj.Class  
  91.                 }, {  
  92.                     "Subject", _Obj.Subject  
  93.                 }  
  94.   
  95.             };  
  96.             Collection_.Insert(Stu_Doc);  
  97.         } catch {  
  98.             throw;  
  99.         } finally {  
  100.             server.Disconnect();  
  101.         }  
  102.     }  
  103.   
  104.     public void Delete_Student_Infromation(Student_Info _Obj) {  
  105.         try {  
  106.             server.Connect();  
  107.             MongoCollection < Student_Info > Collection_ = Database_.GetCollection < Student_Info > ("Student_Information");  
  108.             IMongoQuery Marker = Query.EQ("Student_ID", _Obj.Student_ID);  
  109.             Collection_.Remove(Marker);  
  110.         } catch {  
  111.             throw;  
  112.         } finally {  
  113.             server.Disconnect();  
  114.         }  
  115.     }  
  116.   
  117.     public void Update_Student_Information(Student_Info _Obj) {  
  118.         try {  
  119.             server.Connect();  
  120.             MongoCollection < Student_Info > Collection_ = Database_.GetCollection < Student_Info > ("Student_Information");  
  121.             IMongoQuery Marker = Query.EQ("Student_ID", _Obj.Student_ID);  
  122.   
  123.   
  124.             IMongoUpdate Update_ = MongoDB.Driver.Builders.Update.Set("Name", _Obj.Name)  
  125.                 .Set("Class", _Obj.Class)  
  126.                 .Set("Subject", _Obj.Subject);  
  127.             Collection_.Update(Marker, Update_);  
  128.         } catch {  
  129.             throw;  
  130.         } finally {  
  131.             server.Disconnect();  
  132.         }  
  133.   
  134.     }  
  135.   
  136.     public void Save_Student_Information(Student_Info _Obj) {  
  137.         try {  
  138.             server.Connect();  
  139.             MongoCollection < Student_Info > Collection_ = Database_.GetCollection < Student_Info > ("Student_Information");  
  140.             BsonDocument Stu_Doc = new BsonDocument()  
  141.                 .Add("_id", _Obj._id)  
  142.                 .Add("Student_ID", _Obj.Student_ID)  
  143.                 .Add("Name", _Obj.Name)  
  144.                 .Add("Class", _Obj.Class)  
  145.                 .Add("Subject", _Obj.Subject);  
  146.   
  147.             Collection_.Save(Stu_Doc);  
  148.   
  149.         } catch {  
  150.             throw;  
  151.         } finally {  
  152.             server.Disconnect();  
  153.         }  
  154.     }  
  155. }  
After completion of above setup now we perform CRUD operation.

Database

For this project we create a collection with “Student_Information” name and insert the following record into this collection.
  1. /* 1 */  
  2. {  
  3.     "_id": ObjectId("55fa5661f8677d20935445a0"),  
  4.     "Student_ID": 1001,  
  5.     "Name""Pankaj Choudhary",  
  6.     "Class": 10,  
  7.     "Subject""Hindi"  
  8. }  
  9.   
  10. /* 2 */  
  11. {  
  12.     "_id": ObjectId("55fa5cc3f8677d20935445a1"),  
  13.     "Student_ID": 1002,  
  14.     "Name""Sandeep Jangid",  
  15.     "Class": 11,  
  16.     "Subject""English"  
  17. }  
  18.   
  19. /* 3 */  
  20. {  
  21.     "_id": ObjectId("55fa5ce2f8677d20935445a2"),  
  22.     "Student_ID": 1003,  
  23.     "Name""Sanjeev Baldia",  
  24.     "Class": 12,  
  25.     "Subject""English"  
  26. }  
  27.   
  28. /* 4 */  
  29. {  
  30.     "_id": ObjectId("55fa5cf6f8677d20935445a3"),  
  31.     "Student_ID": 1004,  
  32.     "Name""Rahul Prajapat",  
  33.     "Class": 11,  
  34.     "Subject""Hindi"  
  35. }  
  36.   
  37. /* 5 */  
  38. {  
  39.     "_id": ObjectId("55fa5d15f8677d20935445a4"),  
  40.     "Student_ID": 1005,  
  41.     "Name""Nitin Yadav",  
  42.     "Class": 12,  
  43.     "Subject""Math"  
  44. }  
  45.   
  46. /* 6 */  
  47. {  
  48.     "_id": ObjectId("55fa5d2ff8677d20935445a5"),  
  49.     "Student_ID": 1007,  
  50.     "Name""Sonu",  
  51.     "Class": 12,  
  52.     "Subject""Punjabi"  
  53. }  
  54.   
  55. /* 7 */  
  56. {  
  57.     "_id": ObjectId("55fa5d5cf8677d20935445a6"),  
  58.     "Student_ID": 1008,  
  59.     "Name""Pradeep Yadav",  
  60.     "Class": 12,  
  61.     "Subject""Math"  
  62. }  
Firstly, we start a MongoDB server, for this open a command prompt and run “mongod” command.

MongoDB server

Now run the project in any browser . MongoDB_Form.aspx page looks like the following:

MongoDB

Now we read all CRUD operations.

Select Command

To retrieve the record from “Student_Infromation” collection we are using the following code.
  1. public MongoDB_Class() {  
  2.     Settings_ = new MongoServerSettings();  
  3.     Settings_.Server = new MongoServerAddress("localhost", 27017);  
  4.     server = new MongoServer(Settings_);  
  5.     Database_ = server.GetDatabase("Temp");  
  6.   
  7.   
  8. }  
  9.   
  10. public List < Student_Info > Retrieve_Student_Information() {  
  11.     try {  
  12.         server.Connect();  
  13.         List < Student_Info > Student_List = new List < Student_Info > ();  
  14.         var StuInfo = Database_.GetCollection < Student_Info > ("Student_Information");  
  15.   
  16.         foreach(Student_Info Stu in StuInfo.FindAll()) {  
  17.             Student_List.Add(Stu);  
  18.         }  
  19.   
  20.         return Student_List;  
  21.     } catch {  
  22.         throw;  
  23.     } finally {  
  24.         server.Disconnect();  
  25.     }  
  26. }  
In above code first we created a setup for MongoDB connection. In this setup we provide server address and name of the database. In Retrieve_Student_Information method we created a list of Student_Info type and used this list to store the data of Student_Information collection.

Insert Command
  1. MongoCollection < Student_Info > Collection_ = Database_.GetCollection < Student_Info > ("Student_Information");  
  2. BsonDocument Stu_Doc = new BsonDocument {  
  3.     {  
  4.         "Student_ID", _Obj.Student_ID  
  5.     }, {  
  6.         "Name", _Obj.Name  
  7.     }, {  
  8.         "Class", _Obj.Class  
  9.     }, {  
  10.         "Subject", _Obj.Subject  
  11.     }  
  12.   
  13. };  
  14. Collection_.Insert(Stu_Doc);  
In this code section we created a MongoDB collection that is “Collection_” , this collection represent the “Student_Information” collection. We also created a Bson document(Stu_Doc) for “Student_Information” collection and insert the value in Stu_Doc document that is retrieved from “MongoDB_Form” page into Collection_.

Let us take an example.

Firstly, we create a document.

create a document

Now check the “Student_Information” collection.

record

We can see the item has been added successfully.

Remove Command

We write the following code to perform the delete operation.
  1. MongoCollection<Student_Info> Collection_ = Database_.GetCollection<Student_Info>("Student_Information");  
  2. IMongoQuery Marker = Query.EQ("Student_ID", _Obj.Student_ID);  
  3. Collection_.Remove(Marker);  
In above code we create a MongoCollection and a IMongoQuery Marker, this marker represent the MongoDB match query. We write the the following code or marker:
  1. IMongoQuery Marker = Query.EQ("Student_ID", _Obj.Student_ID)  
  2. Collection_.Remove(Marker);   
Above code removes (delete) all the documents from “Student_Information” collection that match the value of Student_ID field.

Example

We try to delete the record where Student_ID is equal to 1005.

We can see the record of student doesn’t exist whose “Student_ID” is 1005.
record of student
Update Command
  1. MongoCollection<Student_Info> Collection_ = Database_.GetCollection<Student_Info>("Student_Information");  
  2. IMongoQuery Marker = Query.EQ("Student_ID", _Obj.Student_ID);  
  3.   
  4.   
  5. IMongoUpdate Update_ = MongoDB.Driver.Builders.Update.Set("Name", _Obj.Name)  
  6. .Set("Class", _Obj.Class)  
  7. .Set("Subject", _Obj.Subject);  
  8. Collection_.Update(Marker, Update_);  
We know that Update command in MongoDB mainly take two types parameters match and set parameters.

db.Collection_Name({Match_Parameters},{Set_Parameters})

In above query we send Marker works as Match parameter and Update_ document works as set parameters.

Example

Now we update value for Student_ID 1002.

select a option

Document after update.

update

Save Command
  1. MongoCollection<Student_Info> Collection_ = Database_.GetCollection<Student_Info>("Student_Information");  
  2. BsonDocument Stu_Doc = new BsonDocument()  
  3. .Add("_id", _Obj._id)  
  4. .Add("Student_ID", _Obj.Student_ID)  
  5. .Add("Name", _Obj.Name)  
  6. .Add("Class", _Obj.Class)  
  7. .Add("Subject", _Obj.Subject);  
  8.   
  9. Collection_.Save(Stu_Doc);  
Save command first match the _id field for all document if a document contain same _id value then it will update the fields, otherwise insert a new document in the collection. Now we take both the cases. For save command we must send the value of _id field.

Case 1(_id Already Exist)

We try to save the value where _id is equal to “55fa5d5cf8677d20935445a6”.

Record of “55fa5d5cf8677d20935445a6” id is:

document hasbeen saved

Now we execute Save command and examine the result.

Save command

Case 2: (_id doesn’t Exist)

Now we try to save the value where _id is equal to “55fa5d5cf8677d2093544100”, as we know that this _id doesn’t exist so a new document will insert .

document

Collection after Save command.

new document

Summary

Today we learned how to connect MongoDB using C#. We also learn some basic command. In next article I will explain some advance CRUD operation for MongoDB using C#.

Thanks for reading reading the article.

Up Next
    Ebook Download
    View all
    Learn
    View all