Skip to main content

Retrieve the data from the MongoDB using C# and .NET

Hi,
   After inserting some data into MongoDB collection , here are three ways to retrieve the data from the Mongo DB using C#, Don’t forget to add MongoDB reference to the solution before performing the retrieve operation.

C# code:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Core;

namespace RetrivData
{
    class Program
    {
        static void  Main(string[] args)
        {
            CallMain(args).Wait();
            Console.ReadLine();
        }
        static async Task CallMain(string[] args)
        {
            var conString = "mongodb://localhost:27017";
            var Client = new MongoClient(conString);
            var DB = Client.GetDatabase("test");
            var collection = DB.GetCollection<BsonDocument>("store");
          
    //Method 1
    using (var cursor = await collection.Find(new BsonDocument()).ToCursorAsync())
    {
        while (await cursor.MoveNextAsync())
        {
            foreach (var doc in cursor.Current)
            {
                Console.WriteLine(doc);
            }
        }
    }

    // Method 2
    var list = await collection.Find(new BsonDocument()).ToListAsync();
    foreach (var dox in list)
    {
        Console.WriteLine(dox);
    }

 // Method 3
 await collection.Find(new BsonDocument()).ForEachAsync(X=>Console.WriteLine(X));
    
        }
    }
}

Comments

  1. How can we make user search for a specific data (say, search by ID), by Making the user type the specific id in textbox and hit the search button using asp .net c#

    ReplyDelete
    Replies
    1. I tried the following implementation and it seemed to work:
      Here, my collection "store" contains the fields : "email", and "name"
      There are only 2 documents in my collection and hence the output contains output from 2 documents.

      using (var cursor = await collection.Find(new BsonDocument()).ToCursorAsync())
      {
      while (await cursor.MoveNextAsync())
      {
      foreach (var doc in cursor.Current)
      {

      Console.WriteLine(doc["email"]);
      Console.WriteLine(doc["name"]);
      }
      }
      }


      OUTPUT:

      abcd@gmail.com
      Abcd
      lmno@gmail.com
      Lmno

      .........................................................................
      One issue i faced is that, this was possible when I used:
      Console.WriteLine(doc["email"]);

      But only: doc["email"]; didn't work. I'm unable to use the extracted data other than to print in my console.
      .........................................................................

      Hope this was useful!

      Delete
    2. This comment has been removed by the author.

      Delete
    3. Just tried the following piece of code. It seems to work with a "typecast".
      for int, we would need to typecast as (int)doc["field_Name"];
      similarly for float, double, string etc.

      while (await cursor.MoveNextAsync())
      {
      foreach (var doc in cursor.Current)
      {
      string em = (string)doc["email"];
      Console.WriteLine(em);
      }
      }


      This Works!! Hope this helps!!

      Delete
  2. We are really grateful for your blog post. You will find a lot of approaches after visiting your post. Great work

    Data Science Course

    ReplyDelete
  3. Awesome blog. I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work!
    Data Science Training Institute in Bangalore

    ReplyDelete
  4. This is an awesome motivating article.I am practically satisfied with your great work.You put truly extremely supportive data. Keep it up. Continue blogging. Hoping to persuing your next post

    Data Science Training

    ReplyDelete
  5. Great post i must say and thanks for the information. Education is definitely a sticky subject. However, is still among the leading topics of our time. I appreciate your post and look forward to more.
    Best Data Science Courses in Bangalore

    ReplyDelete
  6. Stupendous blog huge applause to the blogger and hoping you to come up with such an extraordinary content in future. Surely, this post will inspire many aspirants who are very keen in gaining the knowledge. Expecting many more contents with lot more curiosity further.

    360DigiTMG Digital Marketing Course

    ReplyDelete
  7. Really wonderful blog completely enjoyed reading and learning to gain the vast knowledge. Eventually, this blog helps in developing certain skills which in turn helpful in implementing those skills. Thanking the blogger for delivering such a beautiful content and keep posting the contents in upcoming days.

    360DigiTMG Cyber Security Course

    ReplyDelete

Post a Comment