I am new to MongoDB and I am using the C# driver, version: v4.0.30319: using MongoDB.Bson; using MongoDB.Driver;
First sorry for this probably being a simple question and I am just not able to find what I need correctly with correct search terms to make this work.
For my project. I am able to connect to the DB, get a list of all the collections, and loop through one of the collections using ASYNC. The problem I am having is trying to find examples to work for simple things like count, limit, or to find/get specific records.
Most of the examples appear to be an older version then what I am using and all what I can find requires ASYNC.
Here is a function I have that is working and returning data.
I want to be able to have a function that works that will and return sub sets of data (using a query), get a count, and other simple things.
My data in the collection is:
_id
RocketRequestID int
LoanRocketID int
RequestDate date
CreatedByID int
RequestXML string/xml doc
My function is:
static async Task<int>MainAsync()
{
int CountRecords = 0;
var client = new MongoDatabaseConnection().mongoConn();
IMongoDatabase db = client.GetDatabase("Viper");
var collection = db.GetCollection<BsonDocument>("RocketRequest");
using (IAsyncCursor<BsonDocument> cursor = await collection.FindAsync(new BsonDocument()))
{
while (await cursor.MoveNextAsync())
{
IEnumerable<BsonDocument> batch = cursor.Current;
foreach (BsonDocument document in batch)
{
Console.WriteLine(document);
Console.WriteLine();
}
}
}// end using
return CountRecords;
}// end async
Again this is probably something simple and I apologize but appreciate any help you can give.
You could create an object to map to your collection:
public class RocketRequest
{
public string Id { get; set; }
public int RocketRequestID { get; set; }
public int LoanRocketID { get; set; }
public DateTime RequestDate { get; set; }
public int CreatedByID { get; set; }
public string RequestXML { get; set; }
}
Then try using Linq by adding the following using statement
using MongoDB.Driver.Linq;
You can then write simpler queries like (for example)
var collection = db.GetCollection<RocketRequest>("RocketRequest");
var count = collection.AsQueryable<Employee>()
.Count();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With