Overview Of MongoDB

Introduction

Are you hearing a lot about NoSQL and want to have a sneak peek? Are you looking for quick Hands-on examples on MongoDB? Do you need a small tutorial on using the latest MongoDB driver (>Version 2.3.0) with C#?

You are at right place.

This article explains the basics of MongoDB, doing CRUD operations on it using command prompt, and then CRUD operations with a sample ASP.NET WebAPI.

What is NoSQL?

NoSQL is a lightweight database which can also be called as “Not Only SQL” or “Non - SQL”. With more and more data flowing around the world every day, traditional relational Databases are facing many problems like scalability, difficulty in analyzing unstructured Data, performance concerns with Big Data, etc. NoSQL databases were designed to overcome these limitations.

Unlike RDBMS, NoSQL databases don’t store data in the form of tables & relations. Based on the Data Distribution, Architecture, Development mode, Data model, etc., different types of NoSQL databases are designed.

Let’s see about MongoDB

MongoDB is one of the noticeable NoSQL databases. It is open source software and can be installed on any operating system like Windows, MAC & Linux. Mongo stores the data in the form of documents & collections. The structure of Mongo DB looks like below.

MongoDB

In MongoDB, each database splits into multiple collections (Like Tables in RDBMS). And each collection consists of various documents (Like Rows in RDMBS). Each document has several Fields in it (Like Columns in RDBMS). The schema of documents will be in JSON format. There can be nested objects inside the schema.

For example, below snippet defines schema of products collection

MongoDB
It is not mandatory to define a schema for a collection. A Collection can contain different types of documents like {"message" : "Hello, world!"},{"roll" : 5}. However, these are case sensitive and the keys for a document cannot be duplicated like {"message" : "Hello, world!", "message" : "Hello, Mongo!"}

Let us explore more on MongoDB step by step with examples.

Initial Setup

  1. Install the latest version of MongoDB from here. Change the installation folder to D drive.
  2. Create a folder under the location D:\data\db. Mongo saves the data by default to this path as it is installed in D drive.
  3. To start Mongo Server, go to command prompt, navigate to the installation folder and run exe as shown below.

    MongoDB

  4. This will initialize the server on the port 27017 by default and waits for the connections.
  5. If you want to change the default “port” number and default “dbpath”, use the below command.

    MongoDB

CRUD Operations

Now, we have started the MongoDB server. Let us do some CRUD (Create, Read, Update and Delete) operations on it through Command Prompt.

  1. Open another command prompt, navigate to the installation folder and run the command Mongo.exe. Now, this command prompt is a client to interact with the MongoDB.

    MongoDB

  2. This command will show the version of MongoDB shell and will also display its connected database name.
  3. Give command “db”, to check the connected database manually as shown below.

    MongoDB

  4. For connecting to another database, provide Use command like “use <DBName >”.

    MongoDB

    Here, if UsersDB exists, mongo will point to that database. Otherwise, it will create and switch to that.
  1. To create a new or use an existing collection, give the command as “<CollectionName>” as shown below.

    MongoDB

  2. MongoDB stores the data in the form of documents which consists of JSON data with Field & Value pairs. Mongo encodes this JSON data to binary and then store them. So this format is called BSON (Binary JSON).

    Below snippet explains the insert operation to a Mongo Collection. Here, “user” is a JSON object with fields & values.

    MongoDB
    Now, the command “db.Users.insert(user)” will insert data to Users Collection as shown below.

    MongoDB
  1. To get all the values in the collection, command “Users.find()” should be provided.

    MongoDB

  2. To get the data in formatted manner, provide the command “Users.find().pretty()”.

    MongoDB
    • From the above output, we can identify that Mongo has added a field “_id” which was not supplied by us. This field is similar to primary key in RDBMS.
    • Since we didn’t provide “_id” field, Mongo will create it through ObjectId. ObjectId is a BSON type, which generates 12 bytes of unique key based on the time, machine identifier, process id, etc.
    • We can also provide “_id” along with the data. But this value should always be unique.
  1. For querying the collection, find should be used along with the condition as shown below.

    MongoDB

    This command is similar to “SELECT * FROM Users WHERE name LIKE '%Patricia%'”
  1. We can use conditional operators to query the data as shown below.

    MongoDB

    Here, “$gt:4” command was used to get all the documents which have id greater than 4. Similarly, more operators like $eq, $ne, $lt, etc. can be used. Please refer Mongo Docs for more operators.
  1. To get all the values based on the field name, “distinct” command should be used as below.

    MongoDB

  1. For updating the collections in MongoDB, we require two parameters.
    • The first parameter is similar to the parameter for “find”e., the condition for the matching document.
    • The second parameter is new field & value pairs.

      MongoDB

      In the above example, the second parameter is containing only Company along with its value. But on running this command, the entire document with id=4 gets replaced as shown below.

      MongoDB

      This action will be useful when a document needs to be replaced with new one. But to modify a single field in the collection, $set command should be used.

      MongoDB

      Similarly, “$unset” will remove a field from the collection as shown below.

      MongoDB
  1. Use “remove()” command for removing a full document from the collection. Also, pass a parameter to it as shown below.

    MongoDB

  2. For deleting a collection from a database, “drop()” command needs to be used as below.

    MongoDB

This action will reset the database back to “test” database.

Now, we have got some idea about MongoDB & doing basic operations on it. Let us see how these operations can be done programmatically using C#.

So, we are going to use MongoDB driver with Visual Studio and create a sample WebAPI for CRUD operations.

Creating WebAPI

  1. Go to Visual Studio -> Create New Project -> Visual C# -> ASP.NET Web Application.

    MongoDB

  2. Select WebAPI and click ok.

    MongoDB

  3. Install “MongoDB” driver for C# from NuGet package manager console. Make sure the installed version is above 2.3.0.

    MongoDB

  4. Go To Models folder and add a new class “cs” as shown.

    MongoDB

  5. In User.cs, add below properties for the user.

    MongoDB
    Attribute BsonId from MongoDB.Bson Namespace was added here to convey that “id” is nothing but Mongo’s _id field. As we have mentioned it as BsonId, we can give any custom name like “userPk” as well. But if we don’t mention BsonId attribute, by default mongo will consider the property with name “id” as its unique key.
  1. Add a new API controller cs under Controllers folder and add below snippet to it.

    MongoDB

    MongoDB

    Here, MongoClient was instantiated and connected to MongoDB server with default port number 27017. The remaining code is self-explanatory. UsersDB & Users collections were retrieved from MongoDB and assigned to the respective properties.
  1. Next, replace default Get methods as below.

    MongoDB
    “Builders” is a static class in MongoDB driver that helps in using multiple actions like Filtering, Sorting, Updating, Indexing, etc.

    Here, the first method returns all the Users information through GET request without any parameters. Using Filter method in Builders class, the “users” collection will be retrieved.

    Similarly, in the Second method, “users” collection was queried based on userId with Lambda Expression.
  1. Create, Update & Delete operations can be done through Insert, Replace & Delete operations available with Mongo Collections. Please find below code for the same.

    MongoDB

Now, our API controller is ready. Let us test this with Fiddler.

  • Create
    In order to insert data, send a POST Request to the API as shown below. Please make sure to add “Content-Type: application/json; charset=utf-8” to the request. Request body should contain the data in JSON form.
    { "userId":"1", "name": "Chelsey Dietrich", "username": "Kamren", "email": "Lucio_Hettinger@annie.ca", "phone": "(254)954-1289" }

    MongoDB

  • Read
    For reading the data, send a GET Request to the API as shown below.

    MongoDB
    MongoDB

    Navigating to URL also will get the data in XML format.

    MongoDB

  • Update
    For updating the existing collection, send the new user details in the request body with type PUT.

    MongoDB

  • DELETE
    To delete any document from the collection, we have to send the respective userId in the URL as below.

    MongoDB

This RESTful WebAPI can be used in any other client applications and make changes to the MongoDB.

Summary

So far, we have got some basic understanding of MongoDB along with examples. We have learned doing CRUD operations to it using Mongo Shell command prompt as well as through a RESTful WebAPI. Any client application that supports HTTP can consume this WebAPI. But, all the queries in MongoDB are confined to a single collection at a time.

Conclusion

Through this article, we understood the advantages of NoSQL when compared to RDBMS. However, NoSQL can’t replace traditional SQL entirely. These are useful for simple transactions in cloud-based decentralized apps.