MongoDB + Ruby。如何访问文档属性?

问题描述 投票:4回答:2

我想用Ruby试试Mongo。我连接,选择了集合,我可以从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]]

但是,当我检索JSON哈希时,如何访问属性?我需要这样的东西:

data.x
=> 4

to_hash方法给了我相同的BSON :: OrderedHash ...... :(

ruby mongodb bson
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而不是find_one,你得到一个MongoDB :: Cursor这是一个Enumerable,所以你可以像任何其他集合一样迭代它;迭代时光标将返回BSON :: OrderedHash实例,这样你就可以做到这样的事情:

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

如果你想要对象而不是Hashes,那么你必须自己用对象包装MongoDB :: Cursor和BSON :: OrderedHash实例(可能通过Struct)。


0
投票

Mongodb find_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"]
© www.soinside.com 2019 - 2024. All rights reserved.