Unable to cast object of type 'MongoDB.Bson.BsonInt32' to type 'MongoDB.Bson.BsonInt64'. C# driver 1.6 mongo 2.2

1,990 views
Skip to first unread message

John Cole

unread,
Sep 5, 2012, 10:14:15 AM9/5/12
to mongodb...@googlegroups.com
I have a collection with an integer field in it, max value in the collection is 64.  I've been casting to Int32, but just got an error using the AsInt32, so I switched to AsInt64.  Alas, there are documents that now throw

Unable to cast object of type 'MongoDB.Bson.BsonInt32' to type 'MongoDB.Bson.BsonInt64'.

Shouldn't that cast work?  What type of cast can I use that will work with both int32 and int64 values?

Thanks,

John

Robert Stam

unread,
Sep 5, 2012, 10:16:32 AM9/5/12
to mongodb...@googlegroups.com
The AsInt32/AsInt64 are casts that require the underlying BsonValue to already be of the correct type.

You can choose to use ToInt64 instead, which will examine the actual type of the underlying BsonValue and either cast or convert to a 64 bit integer. It also works if the underlying BsonValue is a double or a string.
Reply all
Reply to author
Forward
0 new messages