I'm just wondering how the AsXXX and ToXXX operations work in MongoDb. For example, I have operations like the ones below
var person = new BsonDocument();
person.Add("age", 32);
BsonValue age= person["age"];
Console.WriteLine(age.AsBoolean); //throws an exception
Console.WriteLine(age.ToBoolean()); //True
The AsBoolean()
throws an exception, specifically:
System.InvalidCastException : Unable to cast object of type 'MongoDB.Bson.BsonInt32' to type 'MongoDB.Bson.BsonBoolean'
Whereas ToBoolean()
returns true.
So my question is when to use one than the other? How do they work internally?
The difference is in the type of conversion.
AsXXX (somewhat like as
in C#) is simply a cast. It tries to cast the base BsonValue
to the XXX Type and. If the instance is in fact of the right type the conversion works. If not, you'll get an InvalidCastException
as you did.
ToXXX isn't a cast but a conversion. It contains some logic on how to convert from one BsonValue
to the another and shouldn't throw an exception unless the conversion failed.
In your example the age
is a BsonInt32
so AsBoolean
fails as it tries to cast it to BsonBoolean
but all ToBoolean
does is return false
if the value is 0
and true
otherwise so it can't fail.