dcsimg

WEBINAR:
On-Demand

Virtual Developer Workshop: Containerized Development with Docker


Introduction

A NoSQL database is a document-oriented database system that stores data in a JSON-like format. MongoDB is classified as a Document NoSQL databases. It's one of the most popular and leading representatives of a Document databases system widely used in the industry. MongoDB gives users the ease of use and flexibility of JSON documents with the richness of a lightweight binary format. MongoDB represents JSON documents in a binary-encoded format called BSON. Its implementation is lightweight, fast, and highly traversable.

MongoDB provides drivers that allow you to connect with MongoDB from different programming languages. In this article, I'll demonstrate MongoDB installation, how to work with MongoDB from your .NET applications (C# code), and demonstrate the CRUD functions available from the .NET driver.

Why MongoDB?

MongoDB enables developers to store large volumes of data that have little or no structure. MongoDB is fast and can load a high volume of data and give you flexibility and availability in a Cloud-based environment. MongoDB helps to scale database architecture efficiently and inexpensively. With MongoDB's dynamic schemas, you can develop and release quickly.

MongoDB doesn't keep data in rows; it has documents. All the data for a given record is stored in a single document. From a programmer's point of view, MongoDB manipulates pure JSON files. Refer to the following example of a MongoDB document.

{
   "employeeid" : ObjectId("R8rGt541b1ad7d0c4rcfgt7549"),
   "employeename" : "Tapas Pal",
   "department" : "IT",
   "numberOfArticles" : 50,
   "Address" : [
      "street" : "Some Street",
      "city" : "Kolkata",
      "country" : "India"
   ],
   "companyname" : "XYZ",
   "skills" : [".NET", "JavaScript", "NoSQL", "Node.js", "HTML"]
}

Getting MongoDB

MongoDB is a free and open-source database. You can download it from the link given. MongoDB also provides a big list of drivers for different programming languages to communicate with the database. For use with .NET, we need to install the driver from NuGet package. The .NET driver includes MongoDB.Bson, MongoDB.Driver, and MongoDB.Driver.Core.

A .NET Project to Explain MongoDB Operations

Now, let's create a .NET console application to demonstrate CRUD operations on MongoDB. Make sure you run mongod.exe in the command prompt to keep the MongoDB server up and running while executing the console application.

Step 1

Open Visual Studio and create a C# console application project. Name it MongoDBConsoleApp.

The new console application
Figure 1: The new console application

Step 2

Next, we will need .NET drivers for MongoDB. To install the driver, right-click the solution and go to "Manage NuGet Packages." In the search bar, type "MongoDB" and install the package that appears. See Figures 2 and 3.

The "Manage NuGet Packages" link
Figure 2: The "Manage NuGet Packages" link

Package Manager output
Figure 3: Package Manager output

Step 3

Add the following namespaces in your Program.cs file. These namespaces are for connecting MongoDB and for CRUD operations.

using MongoDB.Driver;
using MongoDB.Bson;

Step 4

Next, we will write code to the CRUD operations. In this example, we will be using the BsonDocument class object to store the data in the MongoDB database.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Driver;
using MongoDB.Bson;
namespace MongoDBConsoleApp
{
   class Program
   {
      static void Main(string[] args)
      {
         try
         {
            MongoClient MongodbClient = new
               MongoClient("mongodb://127.0.0.1:27017");
            // Get Database and Collection
            IMongoDatabase Mongodb =
               MongodbClient.GetDatabase("MyDatabase");
            var MongodbcollList =
               Mongodb.ListCollections().ToList();
            Console.WriteLine("The MongoDB list of collections
               are :");
            foreach (var item in MongodbcollList)
            {
               Console.WriteLine(item);
            }
            var mydocument = Mongodb.GetCollection
               <BsonDocument>("mydocument");

            create(Mongodb, mydocument);
            update(Mongodb, mydocument);
            delete(Mongodb, mydocument);

            var myresultDoc = mydocument.Find(new
               BsonDocument()).ToList();
            foreach (var myitem in myresultDoc)
            {
               Console.WriteLine(myitem.ToString());
            }
         }
         catch (Exception ex)
         {
            Console.WriteLine(ex.Message);
         }

         Console.ReadLine();
      }

      static void create(IMongoDatabase Mongodb, var mydocument)
      {

         BsonElement employeename = new BsonElement("employeename",
            "Tapas Pal");
         BsonDocument empployee = new BsonDocument();
         empployee.Add(employeename);
         empployee.Add(new BsonElement("employeenumber", 123));
         mydocument.InsertOne(empployee);

      }

      static void update(IMongoDatabase Mongodb, var mydocument)
      {
         // UPDATE
         BsonElement updateemployee = new
            BsonElement("employeename", "Tapas1 Pal1");

         BsonDocument updateemployeedoc = new BsonDocument();
         updateemployeedoc.Add(updateemployee);
         updateemployeedoc.Add(new BsonElement("employeenumber",
            1234));

         BsonDocument findemployeeDoc = new BsonDocument(new
            BsonElement("employeename", "Tapas Pal"));

         var updateDoc = mydocument.FindOneAndReplace
            (findemployeeDoc, updateemployeedoc);

         Console.WriteLine(updateDoc);

      }
      static void delete(IMongoDatabase Mongodb, var mydocument)
      {
         // DELETE
         BsonDocument findAnotheremployee = new BsonDocument(new
            BsonElement("employeename", "Tapas1 Pal1"));

         mydocument.FindOneAndDelete(findAnotheremployee);
      }
   }
}

In the preceding code snippet's main method, I retrieved the current DB collection first. Next, I created a BsonDocument object where I stored employee data.

In the create method, I showed how to explicitly create a BsonElement object variable to store a key-value pair of employee objects and then added the object to the BsonDocument object.

In the update method, I directly passed the object as a parameter and found the employee name to update the details.

In the delete method, I deleted the employee created earlier.

Finally, I displayed the list.

Conclusion

In this article, we just saw the basic CRUD operations on MongoDB from .NET applications. I hope it helped you to get a basic understanding. Happy Coding!



About the Author

Tapas Pal

I am working in Microsoft Technology for last 15 years and presently working with Cognizant Technology Solutions, India as Senior Architect. I have completed TOGAF 9.1,Microsoft Certification on .NET 1.1 , .NET 2.0, SQL Server 2005 and Sharepoint. Please visit my Blog - http://tapas-pal.blogspot.com/

Related Articles

Comments

  • There are no comments yet. Be the first to comment!

  • You must have javascript enabled in order to post comments.

Leave a Comment
  • Your email address will not be published. All fields are required.

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date