5

Mongo を Ruby で試してみたい。接続してコレクションを選択すると、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]]

しかし、BSON ハッシュを取得するときにプロパティにアクセスするにはどうすればよいでしょうか? 私はこのようなものが必要です:

data.x
=> 4

to_hashメソッドは私に同じ BSON::OrderedHash を与えます... :(

4

2 に答える 2

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の代わりにfullを使用するfind_oneと、列挙可能なMongoDB :: Cursorが得られるため、他のコレクションと同じように反復できます。反復すると、カーソルはBSON :: OrderedHashインスタンスを返すため、次のようなことができます。

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

ハッシュの代わりにオブジェクトが必要な場合は、MongoDB::CursorインスタンスとBSON::OrderedHashインスタンスを自分でオブジェクトでラップする必要があります(おそらくStructを介して)。

于 2012-04-15T16:39:22.843 に答える
0

Mongodbfind_oneメソッドはハッシュ オブジェクトを返し、find メソッドはカーソル オブジェクトを返します。

Cursor オブジェクトは反復可能であり、通常のハッシュで答えを抽出することができます。

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"]
于 2013-01-24T16:14:59.613 に答える