Skip to main content

Retrieve selected documents from MongoDB collection using C#

Hi,
   Previously we have seen how to retrieve the datafrom MongoDB using C# by passing single value as filter, Here we are going to see retrieve particular records from MongoDB by passing multiple filters using $and (or) & to the find() command. The below code returns the document of ‘ProductName’ as ‘WH-208’ and ‘Price’ as ‘9.20’.

C#:  .Net 4.5 and MongoDB 2.0

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Core;
  
namespace RetrivFindAnd
{
  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");
      var builder = Builders<BsonDocument>.Filter;
      var filt = builder.Eq("Price", "9.20") & builder.Eq("ProductName","WH-208");
      var list =await collection.Find(filt).ToListAsync();

      foreach (var doc in list)
       {
           Console.Write(doc);
       }
     }
   }
}


Comments

  1. Swagg Sauce, manufacturer of the finest premium vape juice and salt nicotine ingredients crafted with our signature flavor blends and eliquid online. Premium grade vape juice, candy, cream, custard, dessert, fruit, tobacco, menthol and more. For more information click my website https://speakerdeck.com/swaggsauce1

    ReplyDelete
  2. American Lifeguard offering Lifeguard Association Lifeguard Training & Certification Lifeguarding Classes Lifeguard Training Courses Lifeguard Recert for more information visit website https://disqus.com/by/disqus_C1Ptb8p5ZU/.

    ReplyDelete

Post a Comment