If you’re a close-to-the-metal sort of developer who eschews conveniences like relationships, indexes, and query APIs, then check out Mongomatic from Ben Myles. Mongomatic aims to do ‘just enough’ by mapping your models to MongoDB collections but leaves the rest to you:

  • No additional query API. You simply drop down to the Ruby driver.
  • No relationships. Simply write your own finder methods.
  • No validations. Unless you write your own.

What’s the upside you may ask? Minimal dependencies and better alignment with MongoDB native conventions.

A sample model

require 'mongomatic'

class User < Mongomatic::Base
  def validate
    self.errors << ["Name", "can't be empty"]  if self["name"].blank?
    self.errors << ["Email", "can't be empty"] if self["email"].blank?
  end
end

# set the db for all models:
Mongomatic.db = Mongo::Connection.new.db("mongomatic_test")
# or you can set it for a specific model:
User.db = Mongo::Connection.new.db("mongomatic_test_user")

Find a single user:

found = User.find_one({"name" => "Ben Myles"})
=> #<User:0x00000101939a48 @doc={"_id"=>BSON::ObjectID('4c32834f0218236321000001'), "name"=>"Ben Myles", "email"=>"me@somewhere.com"}, @removed=false, @is_new=false, @errors=[]>

Iterate over a cursor, the MongoDB way:

cursor = User.find({"name" => "Ben Myles"})
=> #<Mongomatic::Cursor:0x0000010195b4e0 @obj_class=User, @mongo_cursor=<Mongo::Cursor:0x80cadac0 namespace='mongomatic_test.User' @selector={"name"=>"Ben Myles"}>>
found = cursor.next
=> #<User:0x00000101939a48 @doc={"_id"=>BSON::ObjectID('4c32834f0218236321000001'), "name"=>"Ben Myles", "email"=>"me@somewhere.com"}, @removed=false, @is_new=false, @errors=[]>
found.remove
=> 67
User.count
=> 0
User.find({"name" => "Ben Myles"}).next
=> nil

If you need a quick-and-dirty model for your MongoDB Ruby app, give Mongomatic a look. It looks like a lightweight alternative to MongoMapper and Mongoid.

[Source on GitHub] [Homepage]


Have comments? Send a tweet to @TheChangelog on Twitter.

Subscribe to The Changelog Weekly – our weekly email covering everything that hits our open source radar.