0

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?

5
  • are you make mistake and paste code from another questions: stackoverflow.com/questions/25995286/… ? :) Commented Sep 23, 2014 at 17:55
  • if you have bsonarray then convert it to Array, not to simple types as int and double Commented Sep 23, 2014 at 17:57
  • @razon, that another question is also mine but that question is different and this one is a continuation.. , so this BsonElement which you are seeing in the code above is actually a BsonArray Commented Sep 23, 2014 at 18:16
  • What does your document look like in the server? And, as @razon said, if it's a BsonArray, then convert it to a BsonArray first... Commented Oct 13, 2014 at 14:50
  • @CraigWilson - i answered it as i figured out the solution, it works now.. !! Many thanks !! Commented Oct 14, 2014 at 7:24

1 Answer 1

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"]);
                        }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.