Ruby Driver for MongoDB
MongoDB has approved drivers for many programming languages, including Ruby. These drivers provide a consistent interface and an understandable, language-sensitive API that matches each language’s idioms. Development becomes smooth since the fundamental tasks you carry out in the MongoDB JavaScript shell may frequently be transferred straight over to the Ruby driver.
Installing the Ruby Driver
MongoDB requires the official Ruby driver, accessible as a RubyGem.
- Install RubyGems: The Ruby package management system, RubyGems, must be updated.
- Install the mongo gem: This is the main gem for MongoDB connections.
- Installation of the bson gem, which encodes and decodes Binary JSON (BSON) for the driver, follows. For disc storage and network transmission, MongoDB uses BSON, a lightweight binary data format.
- Install bson_ext (optional, for performance): Installing bson_ext (optional, for performance) provides a C implementation for BSON processing, making operations more efficient.
Connecting to MongoDB
After installing the driver, you can connect to your instance of MongoDB. 27017 is the MongoDB port by default.
require 'rubygems'
require 'mongo'
# Instantiate the client to localhost and connect to the 'tutorial' database
# Replace '127.0.0.1:27017' with your MongoDB host and port if different
$client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'tutorial')
# Store a reference to a specific collection (e.g., 'users')
$users = $client[:users]
puts 'Connected successfully!'
Use this code to connect to a MongoDB server on localhost (127.0.0.1) at port 27017 and select tutorial. A new database will be created by MongoDB following the first data insertion.
Basic CRUD Operations (Create, Read, Update, Delete)
Ruby drivers represent MongoDB documents as Ruby hashes.
Create (Insert Documents)
To add new documents to a collection, you use methods like insert_one (for a single document) or insert_many (for multiple documents). Documents are passed as Ruby hashes.
# Insert a single document
$users.insert_one({
name: 'Alice Smith',
age: 30,
email: 'alice.smith@example.com'
})
# Insert multiple documents
$users.insert_many([
{ name: 'Bob Johnson', age: 25, email: 'bob.johnson@example.com' },
{ name: 'Charlie Brown', age: 35, email: 'charlie.brown@example.com' }
])
puts "Documents inserted."
Read (Query Documents)
MongoDB provides powerful query capabilities. The find method is used to retrieve documents, and find_one to retrieve a single document.
# Retrieve all documents in the collection
puts "All users:"
$users.find({}).each do |doc|
puts doc
end
# Retrieve documents based on a condition (similar to SQL WHERE clause)
puts "\nUsers older than 28:"
$users.find({ age: { '$gt' => 28 } }).each do |doc| # $gt is a MongoDB query operator for "greater than"
puts doc
end
# Find a single document
puts "\nOne user named Alice Smith:"
puts $users.find_one({ name: 'Alice Smith' })
The find method returns a cursor object, which is an iterable object holding the full result set. The Ruby driver automatically iterates over the results, but you can also manually iterate through it.
Update Documents
Updates require at least two arguments: a query selector to identify the document(s) to update and an update document specifying the changes. Update operators like $set are used to modify specific fields.
# Update a single document: Change Alice's email
$users.update_one(
{ name: 'Alice Smith' },
{ '$set' => { email: 'alice@newdomain.com' } }
)
# Update multiple documents: Add a 'city' field to all users named 'Smith'
$users.update_many(
{ name: { '$regex' => 'Smith' } }, # Using a regular expression to match names containing 'Smith'
{ '$set' => { city: 'New York' } }
)
puts "\nDocuments updated."
Delete Documents
The delete_one and delete_many methods are used to remove documents. They take an optional query selector to specify which documents to remove. If no selector is provided, all documents in the collection will be removed.
# Delete a single document
$users.delete_one({ name: 'Bob Johnson' })
# Delete all documents with age greater than or equal to 35
$users.delete_many({ age: { '$gte' => 35 } }) # $gte is "greater than or equal to"
puts "\nDocuments deleted."
Database and Collection Management
The Ruby driver also provides methods for managing databases and collections.
# List all databases
puts "\nDatabases on server:"
$client.database.command({ listDatabases: 1 }).documents.first['databases'].each do |db_info|
puts "- #{db_info['name']}"
end
# Drop a collection
db = $client.use('tutorial')
db['users'].drop
puts "\n'users' collection dropped."
How the Drivers Work (Briefly)
Every MongoDB driver carries out a number of crucial tasks in the background:
- Object ID Generation: They produce the distinct _id values that serve as MongoDB’s default primary keys for documents. Because these Object IDs contain a timestamp, the creation time resolution is accurate to the closest second.
- BSON Serialisation: Drivers translate document representations particular to a certain language (such as Ruby hashes) into and out of BSON, the binary data format that MongoDB uses.
- Wire Protocol Communication: They use a TCP socket to connect to the MongoDB server via the MongoDB wire protocol.
Developer-friendly Ruby drivers abstract low-level information so developers may focus on application logic. It enables high-availability replication and horizontal sharding to distribute reads among replicas and manage huge datasets. For creating scalable and effective online applications, MongoDB and its Ruby driver are therefore an excellent option.