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”.
Step 3: Now select Online option and download the following drivers.
Now check the Bin folder you will find that the following libraries has been added.
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.
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;
-
-
-
-
- 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 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.
-
- {
- "_id": ObjectId("55fa5661f8677d20935445a0"),
- "Student_ID": 1001,
- "Name": "Pankaj Choudhary",
- "Class": 10,
- "Subject": "Hindi"
- }
-
-
- {
- "_id": ObjectId("55fa5cc3f8677d20935445a1"),
- "Student_ID": 1002,
- "Name": "Sandeep Jangid",
- "Class": 11,
- "Subject": "English"
- }
-
-
- {
- "_id": ObjectId("55fa5ce2f8677d20935445a2"),
- "Student_ID": 1003,
- "Name": "Sanjeev Baldia",
- "Class": 12,
- "Subject": "English"
- }
-
-
- {
- "_id": ObjectId("55fa5cf6f8677d20935445a3"),
- "Student_ID": 1004,
- "Name": "Rahul Prajapat",
- "Class": 11,
- "Subject": "Hindi"
- }
-
-
- {
- "_id": ObjectId("55fa5d15f8677d20935445a4"),
- "Student_ID": 1005,
- "Name": "Nitin Yadav",
- "Class": 12,
- "Subject": "Math"
- }
-
-
- {
- "_id": ObjectId("55fa5d2ff8677d20935445a5"),
- "Student_ID": 1007,
- "Name": "Sonu",
- "Class": 12,
- "Subject": "Punjabi"
- }
-
-
- {
- "_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.
Now run the project in any browser . MongoDB_Form.aspx page looks like the following:
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 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 - 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 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.
Now check the “
Student_Information” collection.
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 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:
- 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 student doesn’t exist whose “Student_ID” is 1005.
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 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.
Document after 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 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:
Now we execute Save command and examine the result.
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 .
Collection after Save command.
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.