Search code examples
mongodbmongodb-.net-driver

How to convert MOngoDB.BsonDocumnet to list of collection in c#?


I have MongoDB.BsonDocument, i want to convert that BsonDocument to List of collection, how can i do this one, i paste my sample code below...

try
{
    var server = MongoServer.Create("localhost:27017");
    var db = server.GetDatabase(DATABASE);
    var riskdata = db.GetCollection("TABLESAMPLE");
    var query = Query.EQ("Name", null);
    var results = riskdata.Find(query);
    gridsample.ItemsSource = results;
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

but above code not working for me...."_id" only binding to grid, remaining fields are not coming.


Solution

  • It is likely that your grid does not understand BsonDocument.

    You need to take a look at serializing those BSON documents into classes.

    It will look something like this:

    class MyDocument { 
        public string name { get; set; }
    
        public int a { get; set; }
    
        public int b { get; set; }
    }
    

    Then you change your find to return these things

    IEnumerable<MyDocument> results = riskdata.FindAs<MyDocument>(query).ToList();
    gridsample.ItemsSource = results;
    

    Now you will have a class with properties that your grid can read.