Evan Evan - 4 months ago 14
C# Question

How to read a Mongo Document and save it to an object?

I need to read certain fields in documents from Mongo. I filtered out a document using the

method but how can I find and store a field in that document? This is my code:

public void human_radioButton_Checked(object sender, RoutedEventArgs e)
Upload human = new Upload(); //opens connection to the database and collection

var filter = Builders<BsonDocument>.Filter.Eq("name", "Human");
race_desc description = new race_desc();
description.desc = Convert.ToString(filter);
desc_textBox.Text = description.desc;

However, this doesn't work since I didn't grab any fields, just the document. So how can I read a field called
and store it into an object?



When you define a filter using the Builders<BsonDocument>.Filter here, you merely define a filter that you can use/execute in a query. Much like storing a SQL string in a string variable.

What you missed here is executing the filter and actually retrieve the data. According to Mongodb C# driver doc:

var collection = _database.GetCollection<BsonDocument>("restaurants");
var filter = Builders<BsonDocument>.Filter.Eq("borough", "Manhattan");
var result = await collection.Find(filter).ToListAsync();

Then you can iterate the results and access the properties like

foreach(var result in results)
   //do something here with result.your_property

And if you just want the first of the result

var result = (await collection.Find(filter).ToListAsync()).FirstOrDefault();

Now if you want to cast the BsonDocument you got now to your own class deserialize document using BsonSerializer:

var myObj = BsonSerializer.Deserialize<YourType>(result);

You can also map it to your own class:

var yourClass = new YourType();
yourClass.Stuff= result["Stuff"].ToString();