Retrieve Operation In MonGoDB Using Robo 3T

In this article, we will learn how to retrieve data from MongoDB. We will learn from the basics because I have written this series of articles focusing on beginners.This article gives some basic understanding of how we retrieve data from the database and display it in our application. In my previous article, we learned the Insert, Delete, and Update operations in MongoDB.You can check that from here

Prerequisites

  • Visual Studio
  • MongoDB installed
  • Robo 3T
You can check how to set up the MongoDB environment from here.
 
Steps to retrieve the data from MongoDB Collection
 
Step 1
 
Open Visual Studio, create a new console application, and rename it as RetrieveOperation.
 
Retrieve Operation In MonGoDB Using Robo 3T

Step 2

Add MongoDB Drivers for C# using NuGet Package Manager.
 
Retrieve Operation In MonGoDB Using Robo 3T 

Step 3

Add the Required Namespace for C#
  1. using MongoDB.Driver;    
  2. using MongoDB.Bson;    
Retrieve Operation In MonGoDB Using Robo 3T 

Step 4

Now, add a connection string.
  1. var connectionString = "mongodb://localhost";    
  2. var Client = new MongoClient(connectionString);   
We want to retrieve data from Employeedetails Table from Employee Database.
  1. var DB = Client.GetDatabase("Employee");    
  2. var collection = DB.GetCollection<BsonDocument>("EmployeeDetails");    

Now, check the complete code.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using MongoDB.Bson;  
  7. using MongoDB.Driver;  
  8.   
  9. namespace RetrieveOperation  
  10. {  
  11.     class Program  
  12.     {  
  13.         static void Main(string[] args)  
  14.         {  
  15.             var connectionString = "mongodb://localhost";  
  16.             var Client = new MongoClient(connectionString);  
  17.             var DB = Client.GetDatabase("Employee");  
  18.             var collection = DB.GetCollection<BsonDocument>("EmployeeDetails");  
  19.             var a =  collection.Find(new BsonDocument()).ToList();  
  20.             foreach (var t in a)  
  21.             {  
  22.                 Console.WriteLine(t);  
  23.             }  
  24.             Console.Read();  
  25.         }  
  26.     }  
  27. }  

 Now run the program and check the Console Screen to check the Data.

Retrieve Operation In MonGoDB Using Robo 3T 
 
We sucessfully retrieved data from the database.
 
Summary
 
In this series of articles we learned basic CRUD operations using C# console applications and MonGoDB. In my next article we will learn Crud Operations in MVC and MongoDB. This article gives you some basic understanding of MonGoDB in C#.