I want to try Mongo with Ruby. I connected, selected collection and I can query data from MongoDB.
irb(main):049:0> coll.find_one({:x=>4})
=> #<BSON::OrderedHash:0x3fdb33fdd59c {"_id"=>BSON::ObjectId('4f8ae4d7c0111ba6383cbe1b'), "x"=>4.0, "j"=>1.0}>
irb(main):048:0> coll.find_one({:x=>4}).to_a
=> [["_id", BSON::ObjectId('4f8ae4d7c0111ba6383cbe1b')], ["x", 4.0], ["j", 1.0]]
But how to access propeties, when I retrieve BSON hash? I need something like this:
data.x
=> 4
to_hash method gives me the same BSON::OrderedHash… 🙁
When you say
coll.find_one({:x=>4}), you get a BSON::OrderedHash back that you access like a normal Hash:If you use a full
findinstead offind_one, you get a MongoDB::Cursor which is an Enumerable so you can iterate it like any other collection; the cursor will return BSON::OrderedHash instances as you iterate so you can do things like this:If you wanted objects instead of Hashes then you’d have to wrap the MongoDB::Cursor and BSON::OrderedHash instances with object yourself (possibly via Struct).