Tuesday, November 11, 2014

Inserting to MongoDB from C#

I have always been a technology enthusiast and like to implement New things .
When I was introduced to mongo DB, an opensource database tool , I wondered how do I perform basic operations thru .Net .
Hence I created a simple application  .
Note : Mongo DB is NoSQL database and not Relational Database Like MSSQL or Oracle.

How I did it .

1.       Add MongoDb Dll Reference.
using MongoDB.Bson;
1.       using MongoDB.Driver;
2.       In the Button Click Event Create Mongo Connection
MongoClient monClient = new MongoClient("mongodb://localhost");
3.       Get Database name
       MongoServer ms = monClient.GetServer();
       ms.Connect();
MongoDatabase db = ms.GetDatabase("testdb");

Get Collections(tables)
MongoCollection collection = db.GetCollection<NewProjects>("Projects");

Add a new class similar to the structure u want the schema to be
public class NewProjects
{
       public NewProjects()
       {
              //
              // TODO: Add constructor logic here
              //
       }
    public string ProjectName { get; set; }
    public string ServiceName { get; set; }
    public string DescriptionName { get; set; }

}

Assign Values to each field (Binding the values from Front End )
NewProjects proj=new NewProjects();
              proj.ProjectName=txtProjName.Text;
              proj.ServiceName=txtServiceName.Text;
       proj.DescriptionName=txtdesc.Text;

Finally Hit Insert Command
collection.Insert(proj);

View the Result in the backend database


Observe that Unique ID  is automatically Created .

Values Passed from Front End





PS: I know you may find it little strange to read Json like Documents(records) because Mongodb stores it in json format . so I have  converted these documents from Json like structure to Table format

Here we go




This application was build with Bootstrap JS


No comments:

Post a Comment