Like SQL database, Mongo DB is also a popular DB. The only difference is that it is a non relational database and unstructured database. Here in this blog post, we will demonstrate the database interaction with MongoDB in .NET Core.
Get Start MongoDB Database in .NET Core
Getting StartedHere we will conduct the demonstration with Visual studio 2022 and .Net 8 framework in a console application, where we will perform Mongo DB integration and interaction.
Mongo DB What Is It?
MongoDB is a cross platform open-source document orientation and simplest database where data stores in JSON format. This JSON format is called BSON. It is popular as a NOSQL database or NOSQL DBMS.
It is written in C++ programing language and designed for modern and cloud applications. MongoDB does not have concepts like schema, table and row in SQL because it’s a purely document-oriented database that works with any size and type of data.
BSON stands for Binary JavaScript Object Notation. It is a binary-encoded serialization of JSON documents. BSON has been extended to add some optional non-JSON-native data types, like dates and binary data. BSON can be compared to other binary formats, like Protocol Buffers.
The following demonstration we will be performing in the current blog post
- MongoDB Database Download
- Installation of MongoDB
- Configure MongoDB
- Mongo DB Integration with .Net Core
- Database Interaction
Download and Install MongoDB
Mongo DB software is available on its official MongoDB website. Click on the link and download the latest version based on your operating system. Here we will be going to demonstrate in Windows, hence my recommendation is to download the software that is supported by Windows platform.
MongoDB now currently 7.2 version is available on the MongoDB official site with user interface, click the below link to download. MongoDB Installation is very simple, install it after successfully downloading.
Configure or Setup MongoDB Environment
To enable MongoDB access from anywhere on the development machine in Windows add the MongoDB path to the PATH environment variable. Usually MongoDB is installed at C:\Program Files\MongoDB folder by default if the path is not changed while installing, in PATH environment variable value should be like this.
C:\Program Files\MongoDB\Server\<version_number>\bin
As we installed the MongoDB 7.2 version the path will be as given below
C:\Program Files\MongoDB\Server\7.0\bin
Follow the below steps to add MongoDB path to PATH environment variable in Windows:
- Right click on the window icon of your system.
- Then click on to the System.
- The Settings window will be opened, on the right side panel find the Advanced System Settings and click on it.
- On the system properties window, click on the Environment Variables button.
-
You will get list of variables (User and System) on the in the Environment variables window, select the Path variable in system variable category and click on the Edit button.
- The Edit environment variable window will be appeared. Here you can enter the path of the folder where nodejs is installed.
- Then copy the above path and click on the New button, you will get mouse focuse in gird row. past the copied path.
- Click OK->OK->OK
- You are done with environment variable update.
For macOS/Linux: Verify the directory that MongoDB was installed at, usually in /usr/local/mongodb. Add the resulting path for mongodb to the PATH environment variable.
Database Integration
To the MongoDB in .Net core, MongoDB driver is required. Create a console application and Install the MongoDB driver C# version from NuGet. The following steps guid to install the driver.
- Right click on your project name.
- Go to Manage Nuget Packages and click on it.
- The NueGet window will be appeared, write MongoDb Driver in the search box of Browser tab.
- The MongoDB.Driver library will appear in the list, Install the latest version by clicking on the Install button.
- The installation process will be started, wait till it completes.
- Once the process is completed, you will be done with the MongoDB installation process.
Get Name of Database of Database MongoDB
The following code snippets describes how to get a db list from database and displays in console window.
using MongoDB.Driver;
Console.WriteLine("Mongo DB Database Interation");
Console.WriteLine("----------------------------");
var mongoClient = new MongoClient("mongodb://localhost:27017");
List<string> databases = mongoClient.ListDatabaseNames().ToList();
Console.WriteLine("Database List");
Console.WriteLine("_____________");
int ind = 1;
foreach (var database in databases)
{
Console.WriteLine("{0}: {1}",ind.ToString(), database);
ind++;
}
Console.ReadLine();
Result
Mongo DB Database Interation
-----------------------------------------
Database List
1: SMS
2: admin
3: config
4: local
MongoDB New Database
Following code shippets create a database with MongoDB. The GetDatabase on the client object will create the database if it has not already been created. The insert operation is required as soon as invoke the GetDatabase function otherwise database won't be created.
using MongoDB.Bson;
using MongoDB.Driver;
Console.WriteLine("Mongo DB Database Interation");
Console.WriteLine("----------------------------");
var mongoClient = new MongoClient("mongodb://localhost:27017");
//create a database with mongodb
IMongoDatabase mongo = mongoClient.GetDatabase("TestDatabase");
mongo.GetCollection<BsonDocument>("Students").InsertOne(new BsonDocument() { { "Raghav", "Rajiv" } });
List<string> databases = mongoClient.ListDatabaseNames().ToList();
Console.WriteLine("Database List");
Console.WriteLine("_____________");
int ind = 1;
foreach (var database in databases)
{
Console.WriteLine("{0}: {1}", ind.ToString(), database);
ind++;
}
Console.ReadLine();
The above code snippets create a new MongoDB database and gets a database list of all the available databases.
Result
Mongo DB Database Interation
----------------------------
Database List
_____________
1: SMS
2: TestDatabase
3: admin
4: config
5: local
Drop a Database of Database MongoDB
A database is removed from the server using the DropDatabase method on the DB class. The following code snippets removes the TestDatabase and list outs the available database.
using MongoDB.Bson;
using MongoDB.Driver;
Console.WriteLine("Mongo DB Database Interation");
Console.WriteLine("----------------------------");
var mongoClient = new MongoClient("mongodb://localhost:27017");
mongoClient.DropDatabase("TestDatabase");
List<string> databases = mongoClient.ListDatabaseNames().ToList();
Console.WriteLine("Database List");
Console.WriteLine("_____________");
int ind = 1;
foreach (var database in databases)
{
Console.WriteLine("{0}: {1}", ind.ToString(), database);
ind++;
}
Console.ReadLine();
Result
Mongo DB Database Interation
----------------------------
Database List
_____________
1: SMS
2: admin
3: config
4: local
Summary
Here in this blog Get Start MongoDB Database in .NET Core, we demonstated of mongodb integration and interation. I hope this is helpful to you.
Thanks