How to retrieve values from an array in MongoDB us

2019-09-01 05:10发布

问题:

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?

回答1:

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"]);
                        }