Search code examples
c#mongodbc#-4.0mongodb-.net-drivermongodb-query

Unable to cast BsonArray to BsonInt32


Below is the code, that fetches the bson element first and then its corresponding value, but even the bson value here is being returned as complete 'key: value' pair from the 2nd iteration onwards, it gives a casting error stating unable to cast bson array to bson int32.

I want to fetch only the values of every element and then sum up those values and display them in a new bson element, i am stuck because of the casting error. can someone help me out on this?

foreach (string nestedAmount in document.Names)
                {
                    BsonElement element = document.GetElement(nestedAmount);
                    BsonValue elementValue = element.Value;



                    //summation logic

                }

Solution

  • I just figured out the solution on my own, below is the code that works correctly now

        double Total = 0;    
    
        foreach (BsonDocument nestedDocument in myDocument["doc"].AsBsonArray)
                            {
                                Total += Convert.ToDouble(nestedDocument["amt"]);
                            }