2012-04-15 48 views
4

我想用Ruby嘗試Mongo。我連接,選擇集合,我可以從MongoDB查詢數據。MongoDB + Ruby。如何訪問文檔屬性?

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

但是,如何訪問propeties,當我檢索BSON哈希?我需要的是這樣的:

data.x 
=> 4 

to_hash方法使我有同樣BSON :: OrderedHash ... :(

回答

4

當你說coll.find_one({:x=>4}),你會得到一個BSON :: OrderedHash回你訪問像一個正常的哈希:

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

如果您使用的find_onefind相反,你得到的MongoDB ::遊標是可枚舉的,所以你可以遍歷它像任何其他集合;噸他光標爲你迭代,所以你可以做這樣的事情會返回BSON :: OrderedHash實例:

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

如果你需要的物體,而不是哈希值,那麼你就必須來包裝的MongoDB ::光標和BSON ::用自己的對象OrderedHash實例(可能通過Struct)。

0

Mongodb find_one方法返回散列對象,find方法返回光標對象。

光標對象可以迭代,然後可以在正常散列中提取答案。

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