I'm using the Mongo .Net Driver to query a MongoDB database and I want to map the returned Bson document to my Customer Object Poco.
In order to do this I created a LoadCustomers()
to return a de-serialized list of customers from the queried Bson document.
In my Customer POCO class, each property is marked with BsonElement
tag which should assist the mapping of Bson to Object.
But when I tried to deserialize using the FindAs<> from this answer , I get a compiler error stating that there is no such method.
How can I return the MongoDB Bson document as a POCO list, using MongoDB .Net driver?
This is my current attempt at the load method:
public static List<Customer> LoadCustomers()
{
var client = new MongoClient(connectionString);
var database = client.GetDatabase("orders");
//Get a handle on the customers collection:
var docs = database.FindAs<Customer>("customers");
return docs;
}
Below is my Customer POCO, showing the fields within the document:
public class Customer
{
/// <summary>
/// This attribute is used to map the Id property to the ObjectId in the collection
/// </summary>
[BsonId]
public ObjectId Id { get; set; }
[BsonElement("firstName")]
public string firstName { get; set; }
[BsonElement("lastName")]
public string lastName { get; set; }
[BsonElement("email")]
public string Email { get; set; }
}
Assuming you are using the latest driver, First you have to get the collection and then do your query on the collection. Something like this
public static List<Customer> LoadCustomers()
{
var client = new MongoClient(connectionString);
var database = client.GetDatabase("orders");
//Get a handle on the customers collection:
var collection = database.GetCollection<Customer>("customers");
var docs = collection.Find(new BsonDocument()).ToListAsync().GetAwaiter().GetResult();
return docs;
}