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
- Insert Operation In MonGoDB Using Robo 3T
- Delete Operation In MonGoDB Using Robo 3T
- Update Operation In MonGoDB Using Robo 3T
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.

Step 2. Add MongoDB Drivers for C# using NuGet Package Manager.

Step 3. Add the Required Namespace for C#
using MongoDB.Driver;
using MongoDB.Bson;

Step 4. Now, add a connection string.
var connectionString = "mongodb://localhost";
var Client = new MongoClient(connectionString);
We want to retrieve data from Employeedetails Table from Employee Database.
var DB = Client.GetDatabase("Employee");
var collection = DB.GetCollection<BsonDocument>("EmployeeDetails");
Now, check the complete code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;
namespace RetrieveOperation
{
class Program
{
static void Main(string[] args)
{
var connectionString = "mongodb://localhost";
var Client = new MongoClient(connectionString);
var DB = Client.GetDatabase("Employee");
var collection = DB.GetCollection<BsonDocument>("EmployeeDetails");
var a = collection.Find(new BsonDocument()).ToList();
foreach (var t in a)
{
Console.WriteLine(t);
}
Console.Read();
}
}
}
Now run the program and check the Console Screen to check the Data.

We successfully 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 rticle gives you some basic understanding of MongoDB in C#.

kalu singh raoPosted Oct 15, 2018, 7:45 AM
Hi Sanwar, Can you present any example based on Users and Roles use in MongoDB ? If any then please share with us. Thanks in advance.
Mahesh ChandPosted Oct 14, 2018, 7:00 AM
Thanks Sanwar. Here is my feedback. Rather than creating multiple short articles, I suggest you create one authoritative article that covers Insert, update, delete, and any other operations. Also, MongoDB does not have a "G" capital. Cheers!
Amit Kumar SinghPosted Oct 13, 2018, 12:34 AM
Thanks Sanwar !!!