Skip to content

Instantly share code, notes, and snippets.

@nosajhpled
Created December 4, 2022 14:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nosajhpled/068c80a4af4808e4ac3cdc673b7f7c90 to your computer and use it in GitHub Desktop.
Save nosajhpled/068c80a4af4808e4ac3cdc673b7f7c90 to your computer and use it in GitHub Desktop.
This code will allow you to send a raw MongoDB query to the server and return back a record set. This will allow you to write queries as if you are writing them for the console.
// Connect to the MongoDB Database/Collection
// Enter your Database name and Collection Name
MongoCollection<BsonDocument> myMongoDB = new MongoClient("mongodb://localhost").GetServer().GetDatabase("Insert Database Name").GetCollection<BsonDocument>("Insert Collection Name");
// Write your query as you would in the MongoDB console
var query = "{somefield : \"some value\"}"; // escape your double quotes inside the string
// loop through the records
foreach (var row in myMongoDB.Find(new QueryDocument(MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(query))))
{
Console.WriteLine(row["somefield"].ToString());
}
#MongoDB#csharp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment