gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 09:13:18 26 4
gpt4 key购买 nike

我想用 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]]

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

data.x
=> 4

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

最佳答案

当你说 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'] }

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

关于ruby - MongoDB + ruby 。如何访问文档属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10163510/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com