MongoDB CRUD Operations Using C#

CRUD Operations In MongoDB

In the MongoDB articles series I discussed the basic concepts of the 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 the 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 the Online option and download the following drivers.

select Online option

Now check the Bin folder you will find that the following libraries have 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 form.

<form id="form1" runat="server">
    <div>
        <div style="background-color:azure;width:100%; height:100px">
            <span style="margin-top:10px; margin-left:200px; font-size:40px; color:coral"> MongoDB CRUD Operations</span>
        </div>

        <div style="margin-top:40px; margin-left:200px">
            <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" AutoGenerateColumns="False">
                <AlternatingRowStyle BackColor="White" />
                <Columns>
                    <asp:BoundField DataField="_id" HeaderText="ObjectID" SortExpression='Eval("_id")'>
                        <ItemStyle Font-Size="X-Large" />
                    </asp:BoundField>
                    <asp:BoundField DataField="Student_ID" HeaderText="Student_ID" ReadOnly="True">
                        <ControlStyle BackColor="#6699FF" />
                        <ItemStyle Font-Size="X-Large" />
                    </asp:BoundField>
                    <asp:BoundField DataField="Name" HeaderText="Student_Name">
                        <ItemStyle Font-Size="X-Large" />
                    </asp:BoundField>
                    <asp:BoundField DataField="Class" HeaderText="Student_Class">
                        <ItemStyle Font-Size="X-Large" />
                    </asp:BoundField>
                    <asp:BoundField DataField="Subject" HeaderText="Student_Subject" SortExpression="Subject">
                        <ItemStyle Font-Size="X-Large" />
                    </asp:BoundField>
                    <asp:TemplateField>
                    </asp:TemplateField>
                </Columns>
                <EditRowStyle BackColor="#7C6F57" />
                <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
                <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
                <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
                <RowStyle BackColor="#E3EAEB" />
                <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
                <SortedAscendingCellStyle BackColor="#F8FAFA" />
                <SortedAscendingHeaderStyle BackColor="#246B61" />
                <SortedDescendingCellStyle BackColor="#D4DFE1" />
                <SortedDescendingHeaderStyle BackColor="#15524A" />
            </asp:GridView>
        </div>

        <div style="background-color:blanchedalmond; width:100%; height:50px; margin-top:10px; text-align:justify">
            <span style="margin-top:10px; margin-left:200px; font-size:40px; color:chocolate">Select A Operation</span>
        </div>

        <div style="margin-top:30px">
            <div runat="server" id="Save">
                <table>
                    <tr>
                        <td style="padding-left:200px; font-size:25px">
                            <asp:Label runat="server" Text="ObjectID"></asp:Label>
                        </td>
                        <td style="padding-left:122px">
                            <asp:TextBox runat="server" width="400px" Height="25px" ID="txtObjectID"></asp:TextBox>
                        </td>
                        <td style="padding-left:200px">
                            <asp:Button runat="server" Text="Submit" Height="35px" Width="100px" BackColor="WindowFrame" Font-Bold="true" ID="Button1" OnClick="Submit"></asp:Button>
                        </td>
                    </tr>
                </table>
            </div>

            <table>
                <tr>
                    <td style="padding-left:200px; font-size:25px">
                        <asp:Label runat="server" Text="Student_ID"></asp:Label>
                    </td>
                    <td style="padding-left:50px">
                        <asp:TextBox runat="server" width="400px" Height="25px" ID="txtStudentID"></asp:TextBox>
                    </td>
                    <td style="padding-left:200px">
                        <asp:Button runat="server" Text="Insert" Height="35px" Width="100px" BackColor="Green" Font-Bold="true" ID="Insert" OnClick="Insert_Record"></asp:Button>
                    </td>
                </tr>
                <tr>
                    <td style="padding-left:200px; font-size:25px">
                        <asp:Label runat="server" Text="Student_Name"></asp:Label>
                    </td>
                    <td style="padding-left:50px">
                        <asp:TextBox runat="server" width="400px" Height="25px" ID="txtStudentName"></asp:TextBox>
                    </td>
                    <td style="padding-left:200px;">
                        <asp:Button runat="server" Text="Update" Height="35px" Width="100px" BackColor="Teal" Font-Bold="true" OnClick="Update_Record"></asp:Button>
                    </td>
                </tr>
                <tr>
                    <td style="padding-left:200px; font-size:25px">
                        <asp:Label runat="server" Text="Student_Class"></asp:Label>
                    </td>
                    <td style="padding-left:50px">
                        <asp:TextBox runat="server" width="400px" Height="25px" ID="txtStudentClass"></asp:TextBox>
                    </td>
                    <td style="padding-left:200px">
                        <asp:Button runat="server" Text="Save" Height="35px" Width="100px" BackColor="Thistle" Font-Bold="true" OnClick="Save_Record"></asp:Button>
                    </td>
                </tr>
                <tr>
                    <td style="padding-left:200px; font-size:25px">
                        <asp:Label runat="server" Text="Student_Subject"></asp:Label>
                    </td>
                    <td style="padding-left:50px">
                        <asp:TextBox runat="server" width="400px" Height="25px" ID="txtStudentSubject"></asp:TextBox>
                    </td>
                    <td style="padding-left:200px">
                        <asp:Button runat="server" Text="Delete" Height="35px" Width="100px" BackColor="Red" Font-Bold="true" OnClick="Delete_Record"></asp:Button>
                    </td>
                </tr>
            </table>
        </div>
    </div>
</form>

Now add the following code in MongoDB_Form.aspx.cs file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MongoDB.Driver;
using MongoDB.Bson;
using System.Data;
using System.Configuration;

namespace WebApplication1
{
    public partial class MongoDBForm : System.Web.UI.Page
    {
        MongoDB_Class _Obj = MongoDB_Class.GetObject();
        Student_Info StuObj_;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Page.FindControl("Save").Visible = false;
                Load_Data();
            }
        }

        public void Load_Data()
        {
            try
            {
                List<Student_Info> Student_List = new List<Student_Info>();
                Student_List = _Obj.Retrieve_Student_Information();
                GridView1.DataSource = Student_List;
                GridView1.DataBind();
            }
            catch (Exception Exp)
            {
                Response.Write(Exp.Message);
            }
        }

        protected void Insert_Record(object sender, EventArgs e)
        {
            try
            {
                StuObj_ = new Student_Info();
                StuObj_.Student_ID = int.Parse(txtStudentID.Text.ToString().Trim());
                StuObj_.Name = txtStudentName.Text.ToString().Trim();
                StuObj_.Class = int.Parse(txtStudentClass.Text.ToString().Trim());
                StuObj_.Subject = txtStudentSubject.Text.ToString().Trim();
                _Obj.Insert_Student_Information(StuObj_);
                Load_Data();
            }
            catch (Exception Exp)
            {
                Response.Write(Exp.Message);
            }
        }

        protected void Update_Record(object sender, EventArgs e)
        {
            StuObj_ = new Student_Info();
            StuObj_.Student_ID = int.Parse(txtStudentID.Text.ToString().Trim());
            StuObj_.Name = txtStudentName.Text.ToString().Trim();
            StuObj_.Class = int.Parse(txtStudentClass.Text.ToString().Trim());
            StuObj_.Subject = txtStudentSubject.Text.ToString().Trim();
            _Obj.Update_Student_Information(StuObj_);
            Load_Data();
        }

        protected void Save_Record(object sender, EventArgs e)
        {
            Page.FindControl("Save").Visible = true;
        }

        protected void Delete_Record(object sender, EventArgs e)
        {
            StuObj_ = new Student_Info();
            StuObj_.Student_ID = int.Parse(txtStudentID.Text.ToString().Trim());
            _Obj.Delete_Student_Infromation(StuObj_);
            Load_Data();
        }

        protected void Submit(object sender, EventArgs e)
        {
            StuObj_ = new Student_Info();
            StuObj_._id = ObjectId.Parse(txtObjectID.Text.ToString().Trim());
            StuObj_.Student_ID = int.Parse(txtStudentID.Text.ToString().Trim());
            StuObj_.Name = txtStudentName.Text.ToString().Trim();
            StuObj_.Class = int.Parse(txtStudentClass.Text.ToString().Trim());
            StuObj_.Subject = txtStudentSubject.Text.ToString().Trim();
            _Obj.Save_Student_Information(StuObj_);
            Load_Data();
            Page.FindControl("Save").Visible = false;
        }
    }
}

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.

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
using System.Web.UI;  
using System.Web.UI.WebControls;  
using MongoDB.Driver;  
using MongoDB.Bson;  
using System.Data;  
using MongoDB.Shared;  
using MongoDB.Driver.Builders;  
using MongoDB.Bson.Serialization;  
  
/// <summary>  
/// Summary description for MongoDB_Class  
/// </summary>  
public class Student_Info {  
    public ObjectId _id {  
        get;  
        set;  
    }  
  
    public Int32 Student_ID {  
        get;  
        set;  
    }  
    public String Name {  
        get;  
        set;  
    }  
    public int Class {  
        get;  
        set;  
    }  
    public String Subject {  
        get;  
        set;  
    }  
}  
public class MongoDB_Class {  
    MongoServerSettings Settings_;  
    MongoServer server;  
    MongoDatabase Database_;  
    public static MongoDB_Class _Obj;  
    public static MongoDB_Class GetObject() {  
        if (_Obj == null) {  
            _Obj = new MongoDB_Class();  
        }  
  
        return _Obj;  
    }  
  
    public MongoDB_Class() {  
        Settings_ = new MongoServerSettings();  
        Settings_.Server = new MongoServerAddress("localhost", 27017);  
        server = new MongoServer(Settings_);  
        Database_ = server.GetDatabase("Temp");  
  
  
    }  
  
    public List < Student_Info > Retrieve_Student_Information() {  
        try {  
            server.Connect();  
            List < Student_Info > Student_List = new List < Student_Info > ();  
            var StuInfo = Database_.GetCollection < Student_Info > ("Student_Information");  
  
            foreach(Student_Info Stu in StuInfo.FindAll()) {  
                Student_List.Add(Stu);  
            }  
  
            return Student_List;  
        } catch {  
            throw;  
        } finally {  
            server.Disconnect();  
        }  
    }  
  
    public void Insert_Student_Information(Student_Info _Obj) {  
        try {  
            server.Connect();  
            MongoCollection < Student_Info > Collection_ = Database_.GetCollection < Student_Info > ("Student_Information");  
            BsonDocument Stu_Doc = new BsonDocument {  
                {  
                    "Student_ID", _Obj.Student_ID  
                }, {  
                    "Name", _Obj.Name  
                }, {  
                    "Class", _Obj.Class  
                }, {  
                    "Subject", _Obj.Subject  
                }  
  
            };  
            Collection_.Insert(Stu_Doc);  
        } catch {  
            throw;  
        } finally {  
            server.Disconnect();  
        }  
    }  
  
    public void Delete_Student_Infromation(Student_Info _Obj) {  
        try {  
            server.Connect();  
            MongoCollection < Student_Info > Collection_ = Database_.GetCollection < Student_Info > ("Student_Information");  
            IMongoQuery Marker = Query.EQ("Student_ID", _Obj.Student_ID);  
            Collection_.Remove(Marker);  
        } catch {  
            throw;  
        } finally {  
            server.Disconnect();  
        }  
    }  
  
    public void Update_Student_Information(Student_Info _Obj) {  
        try {  
            server.Connect();  
            MongoCollection < Student_Info > Collection_ = Database_.GetCollection < Student_Info > ("Student_Information");  
            IMongoQuery Marker = Query.EQ("Student_ID", _Obj.Student_ID);  
  
  
            IMongoUpdate Update_ = MongoDB.Driver.Builders.Update.Set("Name", _Obj.Name)  
                .Set("Class", _Obj.Class)  
                .Set("Subject", _Obj.Subject);  
            Collection_.Update(Marker, Update_);  
        } catch {  
            throw;  
        } finally {  
            server.Disconnect();  
        }  
  
    }  
  
    public void Save_Student_Information(Student_Info _Obj) {  
        try {  
            server.Connect();  
            MongoCollection < Student_Info > Collection_ = Database_.GetCollection < Student_Info > ("Student_Information");  
            BsonDocument Stu_Doc = new BsonDocument()  
                .Add("_id", _Obj._id)  
                .Add("Student_ID", _Obj.Student_ID)  
                .Add("Name", _Obj.Name)  
                .Add("Class", _Obj.Class)  
                .Add("Subject", _Obj.Subject);  
  
            Collection_.Save(Stu_Doc);  
  
        } catch {  
            throw;  
        } finally {  
            server.Disconnect();  
        }  
    }  
}  

After completion of the above setup now perform CRUD operation.

Database

For this project we create a collection with “Student_Information” name and insert the following record into this collection.

/* 1 */  
{  
    "_id": ObjectId("55fa5661f8677d20935445a0"),  
    "Student_ID": 1001,  
    "Name": "Pankaj Choudhary",  
    "Class": 10,  
    "Subject": "Hindi"  
}  
  
/* 2 */  
{  
    "_id": ObjectId("55fa5cc3f8677d20935445a1"),  
    "Student_ID": 1002,  
    "Name": "Sandeep Jangid",  
    "Class": 11,  
    "Subject": "English"  
}  
  
/* 3 */  
{  
    "_id": ObjectId("55fa5ce2f8677d20935445a2"),  
    "Student_ID": 1003,  
    "Name": "Sanjeev Baldia",  
    "Class": 12,  
    "Subject": "English"  
}  
  
/* 4 */  
{  
    "_id": ObjectId("55fa5cf6f8677d20935445a3"),  
    "Student_ID": 1004,  
    "Name": "Rahul Prajapat",  
    "Class": 11,  
    "Subject": "Hindi"  
}  
  
/* 5 */  
{  
    "_id": ObjectId("55fa5d15f8677d20935445a4"),  
    "Student_ID": 1005,  
    "Name": "Nitin Yadav",  
    "Class": 12,  
    "Subject": "Math"  
}  
  
/* 6 */  
{  
    "_id": ObjectId("55fa5d2ff8677d20935445a5"),  
    "Student_ID": 1007,  
    "Name": "Sonu",  
    "Class": 12,  
    "Subject": "Punjabi"  
}  
  
/* 7 */  
{  
    "_id": ObjectId("55fa5d5cf8677d20935445a6"),  
    "Student_ID": 1008,  
    "Name": "Pradeep Yadav",  
    "Class": 12,  
    "Subject": "Math"  
}  

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.

public MongoDB_Class() {  
    Settings_ = new MongoServerSettings();  
    Settings_.Server = new MongoServerAddress("localhost", 27017);  
    server = new MongoServer(Settings_);  
    Database_ = server.GetDatabase("Temp");  
  
  
}  
  
public List < Student_Info > Retrieve_Student_Information() {  
    try {  
        server.Connect();  
        List < Student_Info > Student_List = new List < Student_Info > ();  
        var StuInfo = Database_.GetCollection < Student_Info > ("Student_Information");  
  
        foreach(Student_Info Stu in StuInfo.FindAll()) {  
            Student_List.Add(Stu);  
        }  
  
        return Student_List;  
    } catch {  
        throw;  
    } finally {  
        server.Disconnect();  
    }  
}  

In the above code first, we created a setup for the MongoDB connection. In this setup, we provide the server address and name of the database. In Retrieve_Student_Information method, we created a list of Student_Info types and used this list to store the data of Student_Information collection.

Insert Command

MongoCollection < Student_Info > Collection_ = Database_.GetCollection < Student_Info > ("Student_Information");  
BsonDocument Stu_Doc = new BsonDocument {  
    {  
        "Student_ID", _Obj.Student_ID  
    }, {  
        "Name", _Obj.Name  
    }, {  
        "Class", _Obj.Class  
    }, {  
        "Subject", _Obj.Subject  
    }  
  
};  
Collection_.Insert(Stu_Doc);  

In this code section, we created a MongoDB collection that is “Collection_” , this collection represents the Student_Information collection. We also created a Bson document(Stu_Doc) for Student_Information collection and insert the value in the 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.

MongoCollection<Student_Info> Collection_ = Database_.GetCollection<Student_Info>("Student_Information");  
IMongoQuery Marker = Query.EQ("Student_ID", _Obj.Student_ID);  
Collection_.Remove(Marker);  

In the above code, we create a MongoCollection and an IMongoQuery Marker, this marker represents the MongoDB match query. We write the following code or marker:

IMongoQuery Marker = Query.EQ("Student_ID", _Obj.Student_ID)  
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 a student doesn’t exist whose “Student_ID” is 1005.

record of student

Update Command

MongoCollection<Student_Info> Collection_ = Database_.GetCollection<Student_Info>("Student_Information");  
IMongoQuery Marker = Query.EQ("Student_ID", _Obj.Student_ID);  
IMongoUpdate Update_ = MongoDB.Driver.Builders.Update.Set("Name", _Obj.Name)  
.Set("Class", _Obj.Class)  
.Set("Subject", _Obj.Subject);  
Collection_.Update(Marker, Update_);  

We know that the Update command in MongoDB mainly takes two types of parameters to match and set parameters.

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

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

Example

Now we update the value for Student_ID 1002.

select a option

Document after update.

update

Save Command

MongoCollection<Student_Info> Collection_ = Database_.GetCollection<Student_Info>("Student_Information");  
BsonDocument Stu_Doc = new BsonDocument()  
.Add("_id", _Obj._id)  
.Add("Student_ID", _Obj.Student_ID)  
.Add("Name", _Obj.Name)  
.Add("Class", _Obj.Class)  
.Add("Subject", _Obj.Subject);  
Collection_.Save(Stu_Doc); 

Save command first match the _id field for all document if a document contains the same _id value then it will update the fields, otherwise insert a new document in the collection. Now we take both cases. For the 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 the 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 commands. In the next article, I will explain some advanced CRUD operations for MongoDB using C#.

Thanks for reading reading the article.


Similar Articles