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
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());
}