I save a hash into MongoDB using the Mongo gem. I then get a BSON::Document back when I query the database in Ruby.
How do I convert the BSON::Document back to the original hash?
doc = { name: 'Steve', hobbies: [ 'hiking', 'tennis', 'fly fishing' ] }
result = collection.insert_one(doc)
steve = collection.find( { name: 'Steve' } ).first
returns:
{"_id"=>BSON::ObjectId('5baf68cd65992f3734f396ab'), "name"=>"Steve", "hobbies"=>["hiking", "tennis", "fly fishing"]}
As per the details mentioned in the post it seems like you want to convert BSON db object to json(Hash) object.
BSON contains JSON module which provides the below mentioned method to convert object to json
to_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
result.as_json(only: ["name_of_the_column_you_want"])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With