Ruby Mongo library returns object - ruby

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.

Related

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

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"])

LOAD DATA FROM S3 falsely returns error in codeigniter query method

I´m hosting a codeigniter app on AWS and one method in that app is running a
"LOAD DATA FROM S3 'S3 path' ... "
This is essentially the same as a LOAD DATA INFILE query but customized in AWS Aurora to read files from S3 instead of your local volume. The query executes as expected but CI's
$this->db->error()
returns an array indicating that an error occurred. The content of that array is
[0, '']
First I thought it was a timeout but after reducing the size if the file to import and making sure the records was imported I started to suspect that CI's DB driver aren't designed to handle the result from that query.
The query don´t really return any data and I guess that confuses CI.
Is there any good way to bypass this behavior in CI without altering the frameworks "sourcecode"?
Thanks in advance!
I realized that since the DB driver class called MySQLi returns the following to $this->db instance in the model (see errno and error attributes)
[_mysqli:protected] => mysqli Object
(
[affected_rows] => 1
[client_info] => mysqlnd 5.0.12-dev - 20150407 - $Id: b382534eeb34d9ed79345235b8bae2234b287afcs21ad4e $
[client_version] => 50012
[connect_errno] => 0
[connect_error] =>
[errno] => 0
[error] =>
[error_list] => Array
(
)
I will never get any more information about the error then what mysql_errno and mysql_error returns to the driver. So instead if error checking the query like this
if($this->db->error())
{
return false;
}
I can simply do this
if(is_array($this->db->error()) && 0 !== $this->db->error()[0])
{
return false;
}
Errors are returned in array format or false from $this->db->error() and thus it is very simple to check if the errorcode is zero. If it is zero we can asume that the query executed as planned and that the import has completed.
The reason that we get an array instead of false from $this->db->error() is that no result was returned from the query which CI expects.
So... a simple solution after all.

Getting an object from mongoDB with Mongoid

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.

Mongodb and Ruby gem - Check if record exists

I've a simple Ruby script (no rails, sinatra etc.) that uses the Mongo gem to insert records into my DB as part of a Redis/Resque worker.
Upon occasion instead of doing a fresh insert I'd like to update a counter field on an existing record. I can do this handily enough with rails/mysql. What's the quickest way of doing this in pure Ruby with Mongodb?
Thanks,
Ed
The Ruby client library for MongoDB is very convenient and easy to use. So, to update a document in MongoDB, use something similar to this:
#!/usr/bin/ruby
require 'mongo'
database = Mongo::Connection.new.db("yourdatabasename")
# get the document
x = database.find({"_id" => "12312132"})
# change the document
x["count"] = (x["count"] || 0) + 1
# update it in mongodb
database["collection"].update("_id" => "thecollectionid", x)
You might want to check out the manual for updating documents in MongoDB as well.
thanks to envu's direction I went with upsert in the end. here is an example snippet of how to use it the Ruby client:
link_id = #globallinks.update(
{
":url" => "http://somevalue.com"
},
{
'$inc' => {":totalcount" => 1},
'$set' => {":timelastseen" => Time.now}
},
{
:upsert=>true
}
)

Find documents including element in Array field with mongomapper?

I am new to mongodb/mongomapper and can't find an answer to this.
I have a mongomapper class with the following fields
key :author_id, Integer
key :partecipant_ids, Array
Let's say I have a "record" with the following attributes:
{ :author_id => 10, :partecipant_ids => [10,15,201] }
I want to retrieve all the objects where the partecipant with id 15 is involved.
I did not find any mention in the documentation.
The strange thing is that previously I was doing this query
MessageThread.where :partecipant_ids => [15]
which worked, but after (maybe) some change in the gem/mongodb version it stopped working.
Unfortunately I don't know which version of mongodb and mongomapper I was using before.
In the current versions of MongoMapper, this will work:
MessageThread.where(:partecipant_ids => 15)
And this should work as well...
MessageThread.where(:partecipant_ids => [15])
...because plucky autoexpands that to:
MessageThread.where(:partecipant_ids => { :$in => [15] })
(see https://github.com/jnunemaker/plucky/blob/master/lib/plucky/criteria_hash.rb#L121)
I'd say take a look at your data and try out queries in the Mongo console to make sure you have a working query. MongoDB queries translate directly to MM queries except for the above (and a few other minor) caveats. See http://www.mongodb.org/display/DOCS/Querying

Resources