6

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... :(

asked Apr 15, 2012 at 15:45

2 Answers 2

4

When you say coll.find_one({:x=>4}), you get a BSON::OrderedHash back that you access like a normal Hash:

h = coll.find_one(:x => 4)
puts h['x']
# 4 comes out unless you didn't find anything.

If you use a full find instead of find_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:

cursor = coll.find(:thing => /stuff/)
cursor.each { |h| puts h['thing'] }
things = cursor.map { |h| h['thing'] }

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).

answered Apr 15, 2012 at 16:39
Sign up to request clarification or add additional context in comments.

Comments

0

Mongodb find_one method returns hash object, find method returns cursor object.

Cursor object can be iterated and then is possible to extract the answer in a normal hash.

require 'rubygems'
require 'mongo'
include Mongo
client = MongoClient.new('localhost', 27017)
db = client.db("mydb")
coll = db.collection("testCollection")
coll.insert({"name"=>"John","lastname"=>"Smith","phone"=>"12345678"})
coll.insert({"name"=>"Jane","lastname"=>"Fonda","phone"=>"87654321"})
cursor = coll.find({"phone"=>"87654321"})
answer = {}
cursor.map { |h| answer = h }
puts answer["name"]
lmcanavals
2,3761 gold badge24 silver badges35 bronze badges
answered Jan 24, 2013 at 16:14

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.