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"])
Related
i am following this documentation to view the contents of my Mongodb connection through ruby. However, despite following the code snippet provided in the documentation to display a list of collections:
client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'test')
db.collections # returns a list of collection objects
I receive an empty output...can someone help, thanks.
I need to send a response from a sinatra server with multiple json object.
I have an array of hashes similar to these:
{:a=>5, :school=>"some school"} && {:id=>5, :name=>"michael"}
I would like to append a key to each one say 'school' and 'student' then send that back to the browser in one request like:
[schools:[{werererererwre},{werwrwerwewe}],
student:[{student1}, {student2}]
that's probably not fully formatted json but you understand what I'm trying to do, so then on the frontend I can just go
data.schools
to get an array of the schools
data:{
schools:{
school:{[ ], []}
student: {[], [] }
}
}
Try something like this
Figured it out, here's the spill.
hash = {}
hash[:schools] = {schools hash object}
hash[:students] = {student hash}
hash.to_json
and BOOMSHAKALAKA, DONE!
When trying to find by id I don't get a result using the mongodb driver that comes with Phoenix.
The readme in the mongodb package has the following examples
Mongo.find(MongoPool, "test-collection", %{}, limit: 20)
Mongo.find(MongoPool, "test-collection", %{"field" => %{"$gt" => 0}}, limit: 20, sort: %{"field" => 1})
but when I try like the following I don't get any results.
cursor = Mongo.find(AppName.Repo.Pool, "test-collection", %{"_id" => "1df66b12302b812298308dba"})
Enum.to_list(cursor)
Get [] empty list.
Do I need to convert the id to something first?
I would like to not have to use Ecto all the time.
I figured out the following code that works to convert a string mongo document id to what can be plugged into a mongodb _id parameter
def objectid(id) do
{_, idbin} = Base.decode16(id, case: :mixed)
%BSON.ObjectId{value: idbin}
end
I have the following MongoDB update operation, but it doesnt seem to work, anyone know why?
User.collection.update({ _id: BSON::ObjectId("5018ed448712ff240e0000a0") },
{ "$set" => { name: "ben" } })
It does not throw an error, but just some integer which I am guessing is the doc size.
I am using Mongoid 2.4.10/Rails 3.2.7
If you are using Mongoid, you coule just do a find and update:
User.find("5018ed448712ff240e0000a0").update_attributes!(name: "ben")
or you could use set:
User.find("5018ed448712ff240e0000a0").set(:name, "ben")
Note that set() takes 2 arguments; it does not accept a hash as an argument
Can you use mongoid API instead and use following command:
User.find("5018ed448712ff240e0000a0").set(name: "ben")
Simple enough situation. I've got a MongoDB database with a bunch of information from a previous developer. However I have limited information on the model that came before hand and I DONT have access to the original model class. I've been tinkering with the MongoDB driver to get some more information on it (MongoID will have to be used eventually to map the object back out) as follows.
#The flow is as follows
#Connection
#Databases
#Database
#Collection
#Hash Info
#Setup the connection. you can supply attributes in the form of ("db",portno) but most of the time it will pick up the defaults
conn = Mongo::Connection.new
#Database info
mongodbinfo =conn.database_names
conn.database_info.each { |info| puts info.inspect }
db = conn.db("db_name_here")
db.collection_names.each { |collection| puts collection.inspect }
collection = db.collection("model_name_here")
puts collection.inspect
collection.find.each { |row|
puts row.inspect
puts row.class
}
Each row is a separate object and as MongoDB works, each object/document is a BSON object.
So the bottom line question is How do i de-serialize the BSON into a model using mongoID?
P.s Feel free to use the above code if your trying to figure out a new mongoDB, its been handy for debugging IMHO.
So this was a bust.
In the end I used the Mondb driver to manually pull the data out with queries. However creating the object was far more difficult.
Its better to have the actual model when using ORM.