6.2 Ruby

Data stored in MongoDB can be accessed using the Ruby language. In order to do this, you must install Ruby and the driver ‘ruby-mongo’, which contains the tools to work with MongoDB. In Ubuntu the installation was done using the commands:

sudo apt install ruby
sudo apt install ruby-mongo

To test the access to MongoDB using Ruby the following script was written:

# Load the MongoDB library
require 'mongo'
# Adjust the logger level
Mongo::Logger.logger.level = ::Logger::FATAL
# Establish a connection to the database 'reficio'
conn = Mongo::Client.new([ '127.0.0.1:27017' ], \
    :database => 'reficio')
# View the 'reficio' database collections
conn.collections.each { |coll| puts coll.name }
# Create a cursor for the query
cursor = conn[:pages].find(
    { :title => "Sébastien Auguste Sisson" },
    { :projection => { :title => 1, :excerpt => 1 } }
)
# Display query result
cursor.each { |doc| puts doc }
# Close the connection
conn.close

The execution of this script in the command prompt is shown below:

$ ruby sisson.rb
pages
{"_id"=>BSON::ObjectId('5afc06e526b24ab3365074a7'), "title"=>"Sébastien Auguste Sisson", "excerpt"=>"Sébastien Auguste Sisson, conhecido no também como Sebastião Augusto Sisson e S. A. Sisson, (1824 – 1893) foi um litógrafo, desenhista e biógrafo francês radicado no Brasil. Leia mais na Wikipédia. Livro"}
$

The featured image shows the execution of the script in Visual Studio Code.

6. Programming Languages