Creating .NET Core Console Application With NoSQL- MongoDB At Back-end

In this article, I am going to demonstrate how to create a very simple Microsoft .NET Core - Console Application using NoSQL - MongoDB at back-end. I assume, you have a little understanding about .NET framework connectivity with any RDBMS.

Prerequisite

  1. To work with the application, you need to have Visual Studio 2015 with update 3, in order to have .NET Core (It is my motivation to show you a utility with .NET Core but you can proceed with any version of Visual Studio).

  2. You will have to install NoSQL Database Server MongoDB. You can find it here.

  3. This step is not mandatory but it will be good to have GUI friendly application to manage MongoDB Server. One among many tools you can download and install is Mongobooster [https://mongobooster.com/] -> download. Otherwise, you can also work from the command prompt. I will use parts of both.

Demonstration

You can complete this step by step application in 8 steps. I tried to answer some of the debugging stages in the process. Still, if you find any difficulty, please post in comments section.

  1. Create a folder named 'data' in C: drive and 'db' within 'data' folder. This will be keeping your database. e.g. - C:\data

  2. Now, you have to start the MongoDb instance. To do this, go to C:\Program Files\MongoDB\Server\3.2\bin (I assume that you have installed  or just downloaded MongoDb default instance). Open its bin in command prompt, e.g cd C:\Program   Files\MongoDB\Server\3.2\bin. If you have version 3.4, your path will be e.g cd C:\Program Files\MongoDB\Server\3.4\bin and so.

    Now, execute mongod.exe with parameter --dbpath. Example - C:\Program Files\MongoDB\Server\3.2\bin>mongod.exe --dbpath C:\data\db



    Note - You can also create a Windows Service for the above job to make your life easy next time.

  3. By now, your MongoDB Server is up and running. Don't close this command prompt till end. Open your Mongobooster and go to create and connection. Mongobooster --> Connect --> Create --> (With all default connect port 27017) --> Save and Connect.

    Great ! You are connected with Mongo Server now.

  4. Right click on localhost (Server on left panel) and create a database named 'School'. Then, right click on School database and create Collection. This collection is nothing but your table in RDBMS. Just name it as 'StudentDetails'. Here, a book can be written on Collection, Document, BSON. To check if everything is on track, right click on StudentDetails and select to view document. Don't worry, you will find no records but query in the window.

  5. Now, we are ready with back-end, so come to Visual Studio -> File -> New -> Project -> Console Application (select .NET Core but optional) -> Create.

  6. Right click on reference to get NuGet Package Manager to get the driver to get connectivity with MongoDB. In "Browse", search for MongoDB.Driver driver and install it. For this example, I am using version 2.4.



  7. Replace the below code with that in your Program.cs file.
    1. using System;  
    2.   
    3. //MongoDB.Driver  
    4. using MongoDB.Bson;  
    5. using MongoDB.Driver;  
    6.   
    7. namespace AppTest  
    8. {  
    9.     public class Students  
    10.     {  
    11.         public ObjectId Id { get; set; }  
    12.         public string FirstName { get; set; }  
    13.         public string LastName { get; set; }  
    14.         public string City { get; set; }  
    15.         public string Age { get; set; }  
    16.     }  
    17.   
    18.     public class Program  
    19.     {  
    20.         protected static IMongoClient _client;  
    21.         protected static IMongoDatabase _database;  
    22.   
    23.         public static Students GetStudent()  
    24.         {  
    25.             Console.WriteLine("Please enter student first name : ");  
    26.             string FNm = Console.ReadLine();  
    27.   
    28.             Console.WriteLine("Please enter student last name : ");  
    29.             string LNm = Console.ReadLine();  
    30.   
    31.             Console.WriteLine("Please enter student age : ");  
    32.             string StudentAge = Console.ReadLine();  
    33.   
    34.             Console.WriteLine("Please enter city name : ");  
    35.             string StudentCity = Console.ReadLine();  
    36.   
    37.             Students student = new Students()  
    38.             {  
    39.                 FirstName = FNm,  
    40.                 LastName = LNm,  
    41.                 Age = StudentAge,  
    42.                 City = StudentCity,  
    43.             };  
    44.   
    45.             return student;  
    46.         }  
    47.   
    48.         public void CRUDwithMongoDb()  
    49.         {  
    50.             _client = new MongoClient();  
    51.             _database = _client.GetDatabase("School");  
    52.             var _collection = _database.GetCollection<Students>("StudentDetails");  
    53.   
    54.             Console.WriteLine  
    55.                 ("Press select your option from the following\n1 - Insert\n2 - Update One Document\n3 - Delete\n4 - Read All\n");  
    56.             string userSelection = Console.ReadLine();  
    57.   
    58.             switch (userSelection)  
    59.             {  
    60.                 case "1":   
    61.                     //Insert  
    62.                     _collection.InsertOne(GetStudent());  
    63.                     break;  
    64.   
    65.                 case "2":   
    66.                     //Update  
    67.                     var obj1 = GetStudent();  
    68.   
    69.                     _collection.FindOneAndUpdate<Students>  
    70.                         (Builders<Students>.Filter.Eq("FirstName", obj1.FirstName),  
    71.                             Builders<Students>.Update.Set("LastName", obj1.LastName).Set("City", obj1.City).Set("Age", obj1.Age));  
    72.                     break;  
    73.   
    74.                 case "3":   
    75.                     //Find and Delete  
    76.                     Console.WriteLine("Please Enter the first name to delete the record(so called document) : ");  
    77.                     var deletefirstName = Console.ReadLine();  
    78.                     _collection.DeleteOne(s => s.FirstName == deletefirstName);  
    79.   
    80.                     break;  
    81.   
    82.                 case "4":   
    83.                     //Read all existing document  
    84.                     var all = _collection.Find(new BsonDocument());  
    85.                     Console.WriteLine();  
    86.   
    87.                     foreach (var i in all.ToEnumerable())  
    88.                     {  
    89.                         Console.WriteLine(i.Id + "  " + i.FirstName + "\t" + i.LastName + "\t" + i.Age + "\t" + i.City);  
    90.                     }  
    91.   
    92.                     break;  
    93.   
    94.                 default:  
    95.                     Console.WriteLine("Please choose a correct option");  
    96.                     break;  
    97.             }  
    98.   
    99.             //To continue with Program  
    100.             Console.WriteLine("\n--------------------------------------------------------------\nPress Y for continue...\n");  
    101.             string userChoice = Console.ReadLine();  
    102.   
    103.             if (userChoice == "Y" || userChoice == "y")  
    104.             {  
    105.                 this.CRUDwithMongoDb();  
    106.             }  
    107.         }  
    108.   
    109.         public static void Main(string[] args)  
    110.         {  
    111.             Program p = new Program();  
    112.             p.CRUDwithMongoDb();  
    113.   
    114.               
    115.             //Hold the screen by logic  
    116.             Console.WriteLine("Press any key to trminated the program");  
    117.             Console.ReadKey();  
    118.         }  
    119.     }  
    120. }  
  8. Just run (Crl + F5) the console application.

Conclusion

In this application, I have demonstrated CRUD operation with .NET Core and MongoDB. Demonstrated project is available with the name of AppTest.rar, attached with this article. Additionally, you can learn about customization of BsonDocument to our own format on my blog here. NoSQL can have a different number of columns (fields) in different rows (called document). ID can also be customized instead of FirstName but for this example, I took one quite simple application. CustomizedProject zip is available also, that I have discussed on my blog.

If you like this work, please rate it highly, like/share the post, and subscribe to my profile for more updates. Thanks!