Skip to content

Instantly share code, notes, and snippets.

@taktran
Created January 25, 2012 19:39
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save taktran/1678119 to your computer and use it in GitHub Desktop.
Save taktran/1678119 to your computer and use it in GitHub Desktop.
Mongomapper cheatsheet

Mongomapper cheatsheet

Mongomapper reference

Set up connection

require 'mongo_mapper'

def setup_mongo_connection(mongo_url)
  url = URI(mongo_url)
  MongoMapper.connection = Mongo::Connection.new(url.host, url.port)
  MongoMapper.database = url.path.gsub(/^\//, '')
  MongoMapper.database.authenticate(url.user, url.password) if url.user && url.password
end

setup_mongo_connection('mongomapper://localhost:27017/mongodb-sandbox')

Mongo console

Database shell reference

show dbs	 displays all the databases on the server you are connected to
use db_name	 switches to db_name on the same server
show collections	 displays a list of all the collections in the current database
~$ mongo "mongodb-sandbox"
MongoDB shell version: 2.0.1
connecting to: mongodb-sandbox
> db.teams.findOne()
{
	"_id" : ObjectId("4f0f16c4b01a520778000002"),
	"name" : "Tu Tak Tran's team",
	"pending_users" : [ ],
	"created_at" : ISODate("2012-01-12T17:22:12Z"),
	"updated_at" : ISODate("2012-01-12T17:22:12Z")
}

Common commands

Find

Project.first
Project.find()   # Finds all
TeamMember.find_by_first_name('Billy')
User.find(:account_id => team["_id"])

Create

TeamMember.create(:first_name => "Billy", :last_name => "Corgan")

Delete

Project.delete project.id
Team.pending_users.delete_if {|u| u["id"] == user.id.to_s}    # Where pending_users is an array
TeamMember.first.destroy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment