MongoDB

suggest change

MongoDB is a document-oriented NoSQL database that stores data in flexible, JSON-like BSON (Binary JSON) documents. In the Ruby ecosystem, developers interact with MongoDB through two primary options:

  1. The official Ruby driver (mongo gem): Low-level, high-performance driver providing direct access to collections, commands, and aggregation pipelines.
  2. Mongoid (mongoid gem): An Object-Document Mapper (ODM) that provides an ActiveModel/ActiveRecord-like interface for Ruby and Rails applications.

1. Connecting with the Official mongo Driver

Install the driver:

gem install mongo

Establishing a Connection

require 'mongo'

# Set log level to avoid excessive debug output in development
Mongo::Logger.logger.level = Logger::INFO

# Connect to a standalone MongoDB instance or replica set
client = Mongo::Client.new(
  ['127.0.0.1:27017'],
  database: 'store_db',
  max_pool_size: 10,
  wait_queue_timeout: 5
)

# Select a collection
products = client[:products]

2. CRUD Operations

Inserting Documents

# Insert a single document
result = products.insert_one({
  title: 'Mechanical Keyboard',
  price: 129.99,
  category: 'Electronics',
  in_stock: true,
  tags: ['mechanical', 'usb-c', 'rgb'],
  created_at: Time.now.utc
})

puts "Inserted document ID: #{result.inserted_id}"

# Insert multiple documents in bulk
products.insert_many([
  { title: 'Ergonomic Mouse', price: 69.50, category: 'Electronics' },
  { title: 'Desk Mat', price: 24.00, category: 'Accessories' }
])

Querying Documents (find)

The find method returns a Mongo::Cursor that can be iterated or converted into an array:

# Query with operators ($gt, $in, $regex)
query = {
  price: { '$gte' => 50.00 },
  category: 'Electronics'
}

products.find(query).sort(price: -1).limit(5).each do |doc|
  puts "#{doc[:title]} - $#{doc[:price]} (ID: #{doc[:_id]})"
end

# Find by BSON ObjectId
target_id = BSON::ObjectId.from_string("657f1a2b3c4d5e6f7a8b9c0d")
item = products.find(_id: target_id).first

Updating Documents

# Update a single document using $set and $inc
products.update_one(
  { title: 'Mechanical Keyboard' },
  {
    '$set' => { price: 119.99 },
    '$inc' => { inventory_count: -1 }
  }
)

# Update multiple documents matching criteria
products.update_many(
  { category: 'Accessories' },
  { '$set' => { on_sale: true } }
)

Deleting Documents

# Delete one
products.delete_one(title: 'Desk Mat')

# Delete many
products.delete_many(in_stock: false)

3. Aggregation Pipelines

Aggregation pipelines process documents through multi-stage transformations:

pipeline = [
  # Stage 1: Filter to active items
  { '$match' => { in_stock: true } },

  # Stage 2: Group by category and calculate total / average
  {
    '$group' => {
      _id: '$category',
      total_products: { '$sum' => 1 },
      avg_price: { '$avg' => '$price' },
      max_price: { '$max' => '$price' }
    }
  },

  # Stage 3: Sort by product count descending
  { '$sort' => { total_products: -1 } }
]

results = products.aggregate(pipeline)
results.each do |group|
  puts "Category: #{group[:_id]} | Count: #{group[:total_products]} | Avg: $#{group[:avg_price].round(2)}"
end

4. Object-Document Mapping with Mongoid

Mongoid maps Ruby classes to MongoDB collections using an interface familiar to Rails developers:

gem install mongoid
require 'mongoid'

# Configure Mongoid connection
Mongoid.load_configuration(
  clients: {
    default: {
      database: 'store_db',
      hosts: ['127.0.0.1:27017']
    }
  }
)

class Order
  include Mongoid::Document
  include Mongoid::Timestamps

  # Define schema fields with types
  field :order_number, type: String
  field :total_amount, type: BigDecimal
  field :status,       type: String, default: 'pending'
  field :notes,        type: String

  # Validations
  validates :order_number, presence: true, uniqueness: true
  validates :total_amount, numericality: { greater_than: 0 }

  # Relationships
  embeds_many :line_items
  belongs_to :user, optional: true

  # Scopes
  scope :pending, -> { where(status: 'pending') }
  scope :high_value, -> { where(:total_amount.gte => 1000) }
end

class LineItem
  include Mongoid::Document
  field :sku, type: String
  field :quantity, type: Integer
  field :unit_price, type: Float
  embedded_in :order
end

# Usage:
order = Order.create!(
  order_number: "ORD-2026-001",
  total_amount: 149.99,
  line_items: [
    LineItem.new(sku: "KEY-01", quantity: 1, unit_price: 149.99)
  ]
)

puts "Saved order #{order.order_number} with #{order.line_items.count} items."

5. Indexes and Performance

Always create indexes for fields used frequently in queries, filters, or sorting:

# Create compound index: category ascending, price descending
products.indexes.create_one(
  { category: 1, price: -1 },
  name: 'category_price_idx'
)

# Create unique index (sparse: skip documents that have no sku field)
products.indexes.create_one(
  { sku: 1 },
  unique: true,
  sparse: true
)

Best Practices

  1. Always Reuse the Client Instance: Mongo::Client maintains a connection pool. Do not create a new client per web request; reuse a single global client across your application.
  2. Use Projection to Fetch Only Needed Fields: Reduce network payload and memory consumption by projecting only required keys: products.find({}, projection: { title: 1, price: 1 }).
  3. Handle BSON::ObjectId Conversion: Remember that _id is stored as a BSON::ObjectId, not a plain string. When querying by string ID from URLs, cast using BSON::ObjectId.from_string(id).

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents