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.
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#.