Executing mongosh query using c# mongo driver

Hello, I need to use the mongo driver to run a mongosh command/query in a dotnet c# application. Does this have a method? And if so, how may this be resolved?

Note: I dont want to directly execute the mongosh query using the inbuilt mongosh tool from mongo comapss. I need to run through my .net c# application

Hi @Aadhithya_Aadhithya,

Compass can export a query into most supported languages, unfortunately C# is not yet supported for this.

Its possible to take a query and run it but anything beyond a simple query may as well be done using the driver correctly using the C# idioms.

Having not really used the driver and C# I was able to convert this query to C#

// mongosh query
db.getSiblingDB('sample_mflix').movies.find(
  {genres:'Sci-Fi',year:{$lt:1940}},
  {_id:0,title:1,year:1,directors:1,runtime:1}
).sort(
  {year:-1,runtime:1}
)

I’m sure a C# developer would come up with something more elegant, I have commented a version of each query component just to show that it is possible to use a query from mongosh.

//Program.cs
using MongoDB.Driver;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;

var connectionString = Environment.GetEnvironmentVariable("MONGODB_URI");
if (connectionString == null)
{
    Console.WriteLine("You must set your 'MONGODB_URI' environment variable. To learn how to set it, see https://www.mongodb.com/docs/drivers/csharp/current/quick-start/#set-your-connection-string");
    Environment.Exit(0);
}
var client = new MongoClient(connectionString);
var collection = client.GetDatabase("sample_mflix")
                       .GetCollection<BsonDocument>("movies");

var filterbuilder = Builders<BsonDocument>.Filter; 
var filter = filterbuilder.And(filterbuilder.Eq("genres", "Sci-Fi"),
                               filterbuilder.Lt("year", 1940));
// var filter = BsonSerializer.Deserialize<BsonDocument>("{genres:\"Sci-Fi\",year:{$lt:1940}}");

var projectionbuilder = Builders<BsonDocument>.Projection;
var projection = projectionbuilder.Exclude("_id")
                         .Include("title")
                         .Include("year")
                         .Include("runtime")
                         .Include("directors");
// var projection = BsonSerializer.Deserialize<BsonDocument>("{_id:-1,title:1,year:1,runtime:1,directors:1}");

var sortbuilder = Builders<BsonDocument>.Sort;
var sort = sortbuilder.Descending("year").Ascending("runtime");
// var sort = BsonSerializer.Deserialize<BsonDocument>("{year:-1, runtime:1}");

var results = collection.Find(filter)
                        .Project(projection)
                        .Sort(sort)
                        .ToList();

foreach (var doc in results)
{
    Console.WriteLine(doc.ToBsonDocument());
}

Some resource links on getting started with the C# driver:
https://www.mongodb.com/docs/drivers/csharp/current/
https://www.mongodb.com/developer/languages/csharp/tutorials/