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

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

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"]

Comments

Your Answer

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.