Skip to content

Instantly share code, notes, and snippets.

@jyemin
Last active August 29, 2015 14:13
Show Gist options
  • Save jyemin/393891632df6de1513ab to your computer and use it in GitHub Desktop.
Save jyemin/393891632df6de1513ab to your computer and use it in GitHub Desktop.
Class Cast Hell
var doc = new BsonDocument("x", 10.0);
var x1 = doc["x"].AsInt32; // breaks
var x2 = (int)doc["x"]; // breaks
var x3 = doc["x"].ToInt32(); // ok
collection.createIndex(new BasicDBObject("x", 1)); // covering index
collection.insert(new BasicDBObject("x", 1));
collection.insert(new BasicDBObject("x", 2));
collection.insert(new BasicDBObject("x", 3));
DBObject doc = collection.findOne(new BasicDBObject("x", new BasicDBObject("$lt", 3)), // query
new BasicDBObject("x", 1).append("_id", 0)); // projection
int x = ((Number) doc.get(("x"))).intValue(); // a safe but probably rarely used workaround
x = (Integer) doc.get(("x")); // but this will blow up with a ClassCastException
java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Integer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment