Introduction
I am going to demonstrate how to create a very simple .NET Core Application using NoSQL - MongoDB with C# official driver version 2.4. I assume, you have a little understanding about .NET framework connectivity.
Prerequisite
- 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).
- You will have to install NoSQL Database Server MongoDB. You can find it here.
- 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.
- Create a folder named 'data' in C: drive and 'db' within 'data' folder. This will be keeping your database. e.g. - C:\data
- 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.
- 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.
- 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.
- Now, we are ready with back-end, so come to Visual Studio -> File -> New -> Project -> Console Application (select .NET Core but optional) -> Create.
- 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.
- Replace the below code with that in your Program.cs file.
using System;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson.Serialization.IdGenerators;
using MongoDB.Bson.Serialization;
namespace AppTest
{
public class ProfileIdGenerator : IIdGenerator
{
public object GenerateId(object container, object document)
{
return "Test-"+ Guid.NewGuid().ToString();
}
public bool IsEmpty(object id)
{
return id == null || String.IsNullOrEmpty(id.ToString());
}
}
public class Students
{
[BsonId(IdGenerator = typeof(ProfileIdGenerator))]
public string ProfileId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string City { get; set; }
public string Age { get; set; }
}
public class Program
{
protected static IMongoClient _client;
protected static IMongoDatabase _database;
public static Students GetStudent()
{
Console.WriteLine("Please enter student first name : ");
string FNm = Console.ReadLine();
Console.WriteLine("Please enter student last name : ");
string LNm = Console.ReadLine();
Console.WriteLine("Please enter student age : ");
string StudentAge = Console.ReadLine();
Console.WriteLine("Please enter city name : ");
string StudentCity = Console.ReadLine();
Students student = new Students()
{
FirstName = FNm,
LastName = LNm,
Age = StudentAge,
City = StudentCity,
};
return student;
}
public void CRUDwithMongoDb()
{
_client = new MongoClient();
_database = _client.GetDatabase("School");
var _collection = _database.GetCollection<Students>("StudentDetails");
Console.WriteLine
("Press select your option from the following\n1 - Insert\n2 - Update One Document\n3 - Delete\n4 - Read All\n");
string userSelection = Console.ReadLine();
switch (userSelection)
{
case "1":
_collection.InsertOne(GetStudent());
break;
case "2":
var obj1 = GetStudent();
_collection.FindOneAndUpdate<Students>
(Builders<Students>.Filter.Eq("FirstName", obj1.FirstName),
Builders<Students>.Update.Set("LastName", obj1.LastName).Set("City", obj1.City).Set("Age", obj1.Age));
break;
case "3":
Console.WriteLine("Please Enter the first name to delete the record(so called document) : ");
var deletefirstName = Console.ReadLine();
_collection.DeleteOne(s => s.FirstName == deletefirstName);
break;
case "4":
var all = _collection.Find(new BsonDocument());
Console.WriteLine();
foreach (var i in all.ToEnumerable())
{
Console.WriteLine(i.ProfileId + " " + i.FirstName + "\t" + i.LastName + "\t" + i.Age + "\t" + i.City);
}
break;
default:
Console.WriteLine("Please choose a correct option");
break;
}
Console.WriteLine("\n--------------------------------------------------------------\nPress Y for continue...\n");
string userChoice = Console.ReadLine();
if (userChoice == "Y" || userChoice == "y")
{
this.CRUDwithMongoDb();
}
}
public static void Main(string[] args)
{
Program p = new Program();
p.CRUDwithMongoDb();
Console.WriteLine("Press any key to trminated the program");
Console.ReadKey();
}
}
}
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!