:::: MENU ::::

.NET application with MongoDB – Part 2

On the first post, I introduced about MongoDB briefly and environment setup to work with MongoDB.

On this second post, I will show you how to add MongoDB as a backend database on .Net application by also performing simple CRUD operation.

Here I build a simple WPF application which keeps record of Employee and we are doing CRUD operations with Employee data. Here is UI looks like. This sample is available in github also.

 

First Let’s add MongoDB driver package from nuget. Here is package link.

 

 

Now let’s make a connection with server. Make sure that mongodb server is already up and waiting for connection. If you don’t know how to start server refer part 1 of this series.

I create Employee class as below which gives schema for documents of employee. _id field is mandatory because every document is uniquely identified with  _id. In _id you can pass your own value which is used to uniquely identify  the documents or MOngoDB will automatically add some random number.

I made MongoInstance class where i kept server, database and collection connection like this. When I need database connection of employee collection I will call EmployeeCollection property which will point to Employee collection.

Getting Connection to MongoDB server:

The client instance now holds a pool of connections to the server or servers specified in the connection string. The MongoClient instance actually represents a pool of connections to the database; you will only need one instance of class MongoClient even with multiple threads.

Getting Database:

To get a database, specify the name of the database to the GetDatabase method on client. It’s ok if the database doesn’t yet exist. It will be created upon first use. The database variable now holds a reference to the “EmpDB” database.

Getting a Collection:

To get a collection to operate upon, specify the name of the collection to the GetCollection<TDocument>method on database. It’s ok if the collection doesn’t yet exist. It will be created upon first use. The collection variable now holds a reference to the “EmpRecord” collection in the “EmpDB” database.

When I need connection to Employee Collection i will get connection like this:

You can define separate property for separate collection.

Now let’s perform CRUD operations.

-Create

Once you have the collection (MongoInstance.EmployeeCollection in our case) instance, you can insert documents into the collection.

Create Employee object with data from user input and insert it into Employee Collection. To insert the document in the collection, use the InsertOne or InsertOneAsync methods. To insert multiple documents, you can use the InsertMany or InsertManyAsync methods.

Let’s test Create operation.

You can see log in server too. Here it looks like.

-Read

We are using Find method to query the collection. The Find method returns an IFindFluent<TDocument, TProjection> instance that provides a fluent interface for chaining find operation options. To retrieve all the documents in the collection, call the ToList or ToListAsync methods. This is useful when the number of documents expected to be returned is small.

Here we get Employee Collection instance from MongoHelper.MongoInstance.EmployeeCollection and use Find method to get all documents from Employee Collection.  FilterDefination is base class of filters and Empty property of class FilterDefination<Employee> gets an empty filter. An empty filter matches everything. empListView is ListView to show the Employee records. You can also use LINQ query to filter the document.

-Update

There are numerous update operators supported by MongoDB.

To update at single document, use the UpdateOne or UpdateOneAsync methods to specify the filter and the update document. Here we update the salary field of selected document that meets the filter  Name == [Selected record Name] and set the value of Salary to User input. You can use UpdateMany or UpdateManyAsync methods  to update all documents matching the filter.

 

The update methods return an UpdateResult which provides information about the operation including the number of documents modified by the update. We get no. of Modified document from UpadateResult variable (result in our case).

Now let’s test this operation. Here we update the salary of selected record. In your application you can modify record base on _id of document (if you pass your own data in value of _id) or any other field which you define as a unique like email address.

-Delete

To delete single document use the DeleteOne or DeleteOneAsyncmethods. And for multiple documents matching the filter use the DeleteMany or DeleteManyAsync methods.

In our example we delete the document which Name matched with clicked item Name.. The delete methods return a DeleteResult which provides information about the operation including the number of documents deleted. So here also we get no. of deleted document from deleteresult.

Now, we finished performing basic CRUD operations in mongoDB database through our simple WPF application.. These are the basic operation you can do with MongoDB driver but you can perform other advance task with it. Here is full documentation on what you can do with MongoDB driver for now.

That’s it for now. Another information till date MongoDB driver is not available for WinRT application.

Happy Coding. 🙂