Simple example of using MongoMapper with Ruby

The MongoMapper web site is really lacking on even simple examples, especially those that don’t use Rails. So, here’s a simple example that might help someone.

From the Gemfile:

source 'https://rubygems.org'

gem 'mongo_mapper'

And then the application:

require 'mongo_mapper'


# jam it into the database "mm"
MongoMapper.database = "mm"

class App

def create_user
user = User.new(:name => 'Johnny')
puts "user created"
user.save!
end

def find_user
query = User.where(:name => 'Johnny')
user = query.first # just the first
if not user.nil?
puts user.id
end
end

def delete_user
query = User.where(:name => 'Johnny')
user = query.first # just the first

user.destroy
end
end


class User
include MongoMapper::Document
key :name, String
timestamps!
end

app = App.new()
app.create_user
app.find_user
app.delete_user

The code does a few things:

  1. Creates a new user with a single field called name.
  2. Finds the user using the where function
  3. Removes (destroys/deletes) the user

The key things to note are that the where function returns a query and not the actual results. The results are fetched on demand. This is very similar to the extension methods and LINQ in .NET as those functions build a query that executed only when the results are first requested.

The same thing is true of MongoMapper in this case. The results are not returned until the first function is called. Alternatively, all or last could have been used. all of course returning a list of results that could be iterated in a loop.

If there were no results, the result of calling first in this example would be that the user variable would be nil.

The delete_user function above has absolutely no error checking.