Search code examples
c#.netmongodbserializationmongodb-.net-driver

Dot notation access to MongoDB Query results (BsonDocuments) in C#


How can I access the MongoCursor attributes in C#.

I have the following line of code:

MongoCursor results = collection.Find(searchQuery).SetLimit(10).SetFields(
Fields.Include("name1","name", "_id"));

MongoDB returns an array, each one with two attributes: name and name1. In the results View in the debugger,, I can see an array, each item in the array contains a MongoDB.Bson.BsonDocument.

I want to have a dot notation access to the attributes of each BsonDocument in the Array. How can I achieve this.?


Solution

  • To get values out of a BsonDocument you can use the GetValue/TryGetValue methods or the indexer:

    foreach (var document in results)
    {
        var name1 = document.GetValue("name1");
        var name = document["name"];
    }