Support us on YouTube by Subscribing our YouTube Channel. Click here to Subscribe our YouTube Channel

Friday 11 December 2020

Getting Started with MongoDB Atlas - Part 2

This is the continuation of Getting Started with MongoDB Atlas - Part 1. Our Dataset is ready. Now let’s create a .Net Core Console App through which we will try to access one of the collections in the MongoDB Atlas cluster. 


Give a name to your .Net Core project. Click on the Create button.
Once the solution is ready, right-click on the project’s dependencies and select Manage NuGet Packages.
Now install MongoDB Driver from NuGet package manager as shown in the below image. Click on the Install button, in order to install the package.
In order to connect C# .Net Core Application with the MongoDB Atlas’s Cluster, we need a connection string. Click on the connect button of the Cluster created.
A popup will appear from where we have to choose a connection method. Click on the Connect your application link as shown in the below image.
Select Driver and the Version of the Driver (installed through NuGet package manager) which we are using to connect with MongoDB through the C# .Net Core console application. Click on the copy button in order to copy the connection string. Change <password> to the password added for the database user and <dbname> to the database name with which you want to connect.
There are multiple databases in the Sample Dataset loaded. We will use the sample_mflix database in the connection string.
Now add the below C# Code in the main method of the .Net Core Console Application.

//Passing the connection string in MongoClient

var client = new MongoClient("mongodb+srv://TestUser:PASSWORD@cluster0.maoqh.mongodb.net/sample?retryWrites=true&w=majority");

//Get sample_mflix Database

var db = client.GetDatabase("sample_mflix");

//Get movies collection

var collection = db.GetCollection<BsonDocument>("movies");

//Find document with title Peter Pan

var result=collection.Find("{title:'Peter Pan'}").FirstOrDefault();

Console.WriteLine(result);

Preview:
On running the application, a document with Title “Peter Pan” will be printed on the console.
I hope this will help you in getting started with MongoDB Atlas.

0 comments:

Post a Comment

Subscribe us on YouTube

Subscribe Now

Popular Posts

Contact us

Name

Email *

Message *

Like us on Facebook