Search code examples
c#mongodbmongodb-.net-drivermongodb-query

How to retrieve values from an array in MongoDB using C#


Below in the code that retrieves the elements in the form of a BsonArray. I just want to fetch the numeric value from the array and use that value to calculate the sum.

var fields = "secondary.amount";
    foreach (var document in collection.FindAllAs<BsonDocument>().SetFields(fields))
    {
        foreach (string name in document.Names)
        {
            BsonElement element = document.GetElement(name);                  
            Console.WriteLine("{0}", element.Value);
        }
    }

I tried converting the bson element to an int64, int32, double and then use the numeric value for addition but i get a runtime error of not able to cast a bsonarray etc. Does anyone have any idea on how to go about this?


Solution

  • I figured out the solution, by making the following changes and it works now:

    foreach (BsonDocument nestedDocument in Document["name"].AsBsonArray)
                            {
                                Total += Convert.ToDouble(nestedDocument["amount"]);
                            }