In this blog post we will understand how to use MongoDB as backend
service for our .NET application using C# drivers.
MongoDB
As we know that MongoDB is a NoSQL (i.e. non-relational)
database, which is an open source DBMS stores data in form of documents with
JSON format. NoSQL databases provides high performance and it is easy to
maintain in comparison to any RDBMS (Relational database management system)
when we have to deal with unstructured data for our application.
Configure MongoDB & Robomongo
To use MongoDB within our .NET application first we need to
install MongoDB and Robomongo(Free GUI
tool to use MongoDB) into our system. This is very easy process to install,
configure and use MongoDB.
Steps to configure MongoDB
1.
First we have to download MongoDB. While downloading it, make sure we choose correct
version for windows (i.e. download should fit our system configuration, as for
Windows 8 on a 64 bit processor we need “64
bit 2008 R2+”). Using msi file we
need to install MongoDB.
2.
Make entry inside environment variables: (PATH variable)
“C:\Program
Files\MongoDB\Server\3.0\bin\”.
3.
Default installation location for this will be:
C:\Program Files\MongoDB\Server\3.0
4.
Create a folder named MongoDB at any location
(prefer to create at root level)
For example: D:\MongoDB
5.
In the folder created above we need to create a
folder “data” and inside data folder
create another folder “db”.
6.
Inside MongoDB folder create a text file, name
it to “mongod.cfg” and paste
following code there:
dbpath = D:\MongoDB\data\db
logpath = D:\MongoDB\mongod.log
logappend = true
Note: dbpath & logpath can be changed
as per path for MongoDB folder in system
7.
Create window
service, run the command prompt as “Run
as administrator”. Go to the path to bin folder of MongoDB in our system (i.e.
C:\Program Files\MongoDB).
8.
Run following command:
sc.exe
create MongoDB binPath= "C:\Program
Files\MongoDB\Server\3.0\bin\mongod.exe --service --config=\"D:\MongoDB\mongod.cfg\""
DisplayName= "MongoDB" start= "auto"
After this MongoDB is up and running on our
system as a service.
Steps to configure Robomongo(GUI
tool)
1.
First download robomongo and install it into your system.
2.
Start robomongo
tool and try to configure database. Inside MongoDB connection wizard click
“create” link to establish connection.
Let’s start some coding
Up to this point we have MongoDB and Robomongo installed
into our system. Now this is the time to use MongoDB as DBMS for our application
using C# drivers.
1.
Make sure visual studio installed into system.
Open visual studio and create a sample console application, name it to : “LibraryApplication”
2.
Second step is to install official mongoDB C# drivers’ packages from nuget store. Go to online nuget packages
and type “mongo”. Install both
drivers for application.
3.
Check this step will install few dlls into application:
MongoDB.Bson,
dll deals with BSON document of MongoDB and provides information how to
serialize data from that document.
4.
The first thing , I am going to create a class for
our LibraryApplication project:
public class BookStore
{
public ObjectId Id { get; set; }
public string BookTitle { get; set; }
public string Auther { get; set; }
public string Category { get; set; }
public string ISBN { get; set; }
}
Here notice I have created one
property with type “ObjectId” and
name “Id”. This is the unique
identification for a document in MongoDB. We can have this type with any other
unique property as well. In fact if we will not create any of such property in
class, then MongoDB by default create the same with name _Id, to uniquely identify
that document.
5.
Other step is to establish connection to database
(MongoDB) and try to insert data to our database.
static void Main(string[] args)
{
MongoClient client = new MongoClient();
var server = client.GetServer();
var db = server.GetDatabase("LibraryDB");
var collection = db.GetCollection<BookStore>("BookStore");
BookStore bookStore = new BookStore
{
BookTitle = "MongoDB Basics",
ISBN = "8767687689898yu",
Auther = "Tanya",
Category = "NoSQL DBMS"
};
collection.Save(bookStore);
}
a. Check
the first line of code, “MongoClient”
is used to create a connection to MongoDB. We can also specify the connection string
(with server name, port etc.) to this object. For now I am connecting to local
database server with default port, so don’t need to provide connection string argument
here.
b. Next
line is to get the server connected.
c. Once
server has been connected, then we have to get the database.
d. Next
is to create a collection (can be think of
as a table in RDBMS) and save data
into it.
6.
After executing the program we can see the
magic:
In our database, a new database named “LibraryDB” has been created with
collection “BookStore” and data inserted
in it.
Important feature here is, it will create
new database if not exists and update if already exists. Same is with
collections.
For example if we add another record into a collection:
{
BookTitle
= "C# Basics",
ISBN = "27758987689898yu",
Auther = "Somya",
Category = "Programming Languages"
};
This will add one more document to existing
“Bookstore “collection.
7.
One more important thing is, as I told earlier
we can also set any of our property as unique identification like this:
[BsonId]
public string ISBN { get; set; }
Run the application and check, now ISBN
number will act as unique identification for document. There will not be any
field name ISBN in database in this case.
8.
We can have nullable fields in MongoDB and that
is not shown in document if value is null:
[BsonIgnoreIfNull]
public int? TotalPages { get; set; }
9.
Now let’s query the data from database:
To
get books count having pages more than 200
collection.AsQueryable().Where(b => b.TotalPages > 200);
To
get Book having title starts with 'Mongo’
collection.AsQueryable().Where(b
=> b.BookTitle.StartsWith("Mongo"));
To
get Cheapest Book
collection.AsQueryable().OrderBy(b
=> b.Price).First();
To
get book with a particular ISBN number
collection.AsQueryable().Single(b
=> b.ISBN == "27758987689898yu");
To
remove all collection
collection.RemoveAll();
Summary
So in this article we understood how to use MongoDB in our
.NET applications using C# drivers. How we can insert/ query data from MongoDB using
C# code.
Please stay tuned for more information on MongoDB usage.