Click here to Skip to main content
Click here to Skip to main content
Go to top

Insert, Update, Delete and View using MongoDB in ASP.NET

, 8 Oct 2013
Rate this:
Please Sign up or sign in to vote.
In this post, I am going to show you usage of MongoDB between two tables relationships


In this tip, you can learn how to use mongodb database. I have gone through mongodb site and analysed the database to insert record with table relationships. I would like to help you get started with mongoDB(insert, update, delete, view) with websites using datatable relationships.

About MongoDB

MongoDB is a scalable, open source, high performance, document oriented database developed and supported by the company 10Gen, it is written in C++.

NoSQL is a new trend in database development and refers generally to databases without a fixed schema. MongoDB is one of the newer NoSQL databases developed in 2009. Due to this dynamic schema, MongoDB is highly fit for the solution that follows agile methodology, in other words we will have a definitive deliverable in each sprint where our new releases should not affect another already operational database and schema.

We can use MongoDB as a backend for the applications written in C#. For the same, we need to have a C# Driver that connects to MongoDB. For more details on C# Driver, you can take a look at C# driver for MongoDB.

Once we have connected to MongoDB using the C# driver, we can query MongoDB collections and documents from C# using LINQ.

Class For MongDB

MongoDB is simple to start with and gets more complex over time, which works because a developer’s expertise with the database matures over time. One of the great things about NoSQL, in fact, is the ability to iterate on one’s data model as one’s business requires it. Alright, we have defined one class to maintain the transactions. If you will mark on Employee class, there exists some employee information with departmentId and DeparmentName. Wherever we are inserting departmentid to employee table for the time view, we need departmentname there.

Connectionstring in webconfig

       name="ConnectionString" connectionString="Server=localhost:27017"

Define in DAL Class

The following code will help you in setting the stage for getting connected to MongoDB. We can declare a mongo connection string as “Server=localhost:27017”, create a mongo Server using the mentioned connection string.

Using the Code

First, we have designed the web page where we will manage the data. First of all, I have designed in a plain application to insert Department and then Employee data. I am showing one sample image copy below:

Alternate Text

See in the above design I have marked from department to employee dropdown. It's so simple to do this here I am going to show using mongodb.

Submit the Employee Data

 protected void btnSubmitE_Click(object sender, EventArgs e)
        Employee emp = new Employee();
        if (ViewState["_idE"] != "" && ViewState["_idE"] != null)
            emp._id = ObjectId.Parse(ViewState["_idE"].ToString());
        emp.EmployeeName = txtEmployeeName.Text;
        emp.Age = Convert.ToInt32(txtAge.Text);
        emp.Address = txtAddress.Text;
        emp.City = txtCity.Text;
        emp.DepartmentId = ObjectId.Parse(ddlDepartment.SelectedValue.ToString());

        if (hdnEmployeeOperation.Value == "") dal.InsertEmployee(emp);
        else dal.UpdateEmployee(emp);

Simply Submit button access the object class and fill data object of the class. See emp.DepartmentId is set by ObjectId of dropdown selected value, this is the primary key of department table.

    public void InsertEmployee(Employee emp)
        MongoCollection<employee> document = myDatabase.GetCollection<employee>("Employee");
        BsonDocument Employee = new BsonDocument {
                <strong>{ "DepartmentId", emp.DepartmentId }</strong>

In the above code, initializing MongoCollection for specific employee table from collection of mongo database where BsonDocument is required for inserting data into mongodb. Now insert { "DepartmentId", emp.DepartmentId } to database.

    public List<employee> GetEmployeeList()
        List<employee> lst = new List<employee>();
        var collection = myDatabase.GetCollection<employee>("Employee");
        foreach (Employee memberMap in collection.FindAll())
            memberMap.DepartmentName = GetDepartmentName(memberMap.DepartmentId);
        return lst;
    string GetDepartmentName(ObjectId _id)
        MongoCollection<department> departments = 
        var dep = departments.FindOneById(_id);
        return dep.DepartmentName;

In the above content, I have collected all inserted employee data. But in employee table, I have only DepartmentId, so I have split it outside to collect deparmentname by the id of Department. And GetDepartmentName method returns departmentname. In my opinion, there should be another solution but for easy process created a separated method for this. By this employee list is now listed with departmentid with departmentname. Now we can show its name using its departmentid.

    public void UpdateEmployee(Employee emp)
        MongoCollection<employee> employee = myDatabase.GetCollection<employee>("Employee");
        IMongoQuery query = Query.EQ("_id", emp._id);
        IMongoUpdate update = MongoDB.Driver.Builders.Update.Set("EmployeeName", emp.EmployeeName)
                                                            .Set("Age", emp.Age)
                                                            .Set("Address", emp.Address)
                                                            .Set("City", emp.City)
                                                            .Set("DepartmentId", emp.DepartmentId);
        employee.Update(query, update);
    public void DeleteEmployee(ObjectId _id)
        MongoCollection<employee> employee = myDatabase.GetCollection<employee>("Employee");
        IMongoQuery query = Query.EQ("_id", _id);

But for the other reference using mongodb makes insert, update, delete and view records including table relationships. I hope this article will help many people.

Key Points

First ensure that your mongo server is running, then you can access the mongodb in any application. To get free source of mongodb, just go through MongoDB link is the reference section below. If you want more clarification about my app, just download it. You will get a brief code.



This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

sankarsan parida
Software Developer
India India
Hi all,I am Sankarsan Parida,I am working as a Software Engineer in CTS Kolkata. I have around 4 years of experience in developing the web applications. My areas of interest are C#.Net, Ajax, Sql server, MongoDB, MVC, WCF
Follow on   Google+

Comments and Discussions

GeneralMy vote of 2 PinmemberMayank Patel Devloper22-Jun-14 23:00 
GeneralRe: My vote of 2 Pinprofessionalsankarsan parida23-Jun-14 0:47 
Questioninsert using linq PinmemberMember 995422424-Apr-14 5:43 
AnswerRe: insert using linq Pinprofessionalsankarsan parida24-Apr-14 8:08 
QuestionThank you Pinmembersyed_adnan3-Apr-14 17:50 
AnswerRe: Thank you Pinprofessionalsankarsan parida3-Apr-14 19:38 
QuestionMay I suggest an alternative approach? PinmemberGeorge Swan8-Oct-13 23:35 
AnswerRe: May I suggest an alternative approach? Pinprofessionalsankarshan parida9-Oct-13 1:35 
GeneralRe: May I suggest an alternative approach? Pinprofessionalsankarshan parida9-Oct-13 1:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140926.1 | Last Updated 8 Oct 2013
Article Copyright 2013 by sankarsan parida
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid