According to Wikipedia “MongoDB is a free and open-source cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with schemas. ” So MongoDB is a non-relational database and the terminologies used in this are different compared to relational databases like MSSQL.
I will start by installing MongoDB into the machine. Install it and once the installation is over, the system drive will create a MongoDB folder in the following path C:\Program Files\MongoDB. At the time of writing, the latest stable release is 3.4.4. If you go into the bin folder (C:\Program Files\MongoDB\Server\3.4\bin) you can see a bunch of executables.
Mongod.exe, the third one from the top is the mongo server and mongo.exe is the shell. We will use the shell to connect to the server and perform some operations. Before that we have to make sure that the server is up and running. The rest of the executable files are used for backup and restore, import and export, monitor server etc.
Before going to run the mongo server for the first time you would need to create a directory where the data files reside. The default name for the directory is data\db. Run the following command to create a new directory under C drive
Once that directory exists, you can simply run the mongo server with the keyword “mongod”
If we look into the details displayed in the command prompt you can see that MongoDB has been started, initialize data in directory and up and running at port number 27017 and it is ready to use. We can shut it down cleanly by entering Ctrl+C.
Next thing I’m going to do is to integrate MongoDB into a Web API project. For an application like web api to communicate with MongoDB, is possible only by the use of a client library called driver. MongoDB provides a set of drivers which supports different programming languages and I’m going to use the C# Driver.
Step:1 – Create a new web api project.
Step:2 – Install MongoDB C# driver into the application. Browse “mongodb.driver” in NuGet window and install it. It is the official .NET driver for MongoDB.
Step:3 – I’m going to create a new database called VofoxDB and save employee details in a collection called ‘Employees’. I have created a model class ‘Employee’ and added some properties. The model contains an Id property which will map to the _id field of the document in database. MongoDB uses ObjectIds as the default value of _id field of each document, which is generated while creating any document. By providing the BsonId and BsonType attributes, I have declared Id property as a string and when MongoDB serializes it, it’s internally treated as an ObjectId.
Step 4 – The data access layer contains the set of CRUD operations to manipulate the Employee collection.
Step 5 – I have written api action methods corresponding to the CRUD operations written in data access layer.
You can test this out by using any api tools like Postman, RestClient etc.
Happy Coding 🙂
GET QUICK QUOTE