简体   繁体   English

如何从Ruby中的BSON文档中获取哈希值?

[英]How do I get a hash from a BSON document in Ruby?

I save a hash into MongoDB using the Mongo gem. 我使用Mongo gem将哈希保存到MongoDB中。 I then get a BSON::Document back when I query the database in Ruby. 当我在Ruby中查询数据库时,我得到了BSON :: Document。

How do I convert the BSON::Document back to the original hash? 如何将BSON :: Document转换回原始哈希?

doc = { name: 'Steve', hobbies: [ 'hiking', 'tennis', 'fly fishing' ] } doc = {名称:“史蒂夫”,爱好:[“远足”,“网球”,“钓鱼”]}

result = collection.insert_one(doc) 结果= collection.insert_one(doc)

steve = collection.find( { name: 'Steve' } ).first 史蒂夫= collection.find({name:'Steve'}).first

returns: 收益:

{"_id"=>BSON::ObjectId('5baf68cd65992f3734f396ab'), "name"=>"Steve", "hobbies"=>["hiking", "tennis", "fly fishing"]} {“ _id” => BSON :: ObjectId('5baf68cd65992f3734f396ab'),“名称” =>“史蒂夫”,“兴趣爱好” => [“远足”,“网球”,“飞钓”]}

As per the details mentioned in the post it seems like you want to convert BSON db object to json(Hash) object. 根据文章中提到的详细信息,似乎您想将BSON db对象转换为json(Hash)对象。

BSON contains JSON module which provides the below mentioned method to convert object to json BSON包含JSON模块,该模块提供以下将对象转换为json的方法

to_json

https://www.rubydoc.info/github/mongodb/bson-ruby/BSON/JSON https://www.rubydoc.info/github/mongodb/bson-ruby/BSON/JSON

Not sure of the below mentioned method, as I have only used it in ActiveRecord object, try if it works 不确定下面提到的方法,因为我只在ActiveRecord对象中使用过它,请尝试是否可行

result.as_json(only: ["name_of_the_column_you_want"])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM