#194
Dec 28, 2009

MongoDB and MongoMapper

MongoDB is a document based database engine. Learn how to access it through MongoMapper in this episode.
Tags: models plugins
Download (24.1 MB, 13:13)
alternative download for iPod & Apple TV (15.3 MB, 13:13)

Resources

Note: if you don’t want the long MongoDB IDs in the URL, you can set up any attribute as a permalink.

rails todo
sudo rake gems:install
script/generate nifty_layout
script/generate nifty_scaffold project name:string --skip-migration
script/generate nifty_scaffold task project_id:string name:string completed:boolean --skip-migration
# config/environment.rb
config.gem "mongo_mapper"

# config/initializers/mongo_config.rb
MongoMapper.database = "todo-#{Rails.env}"

# models/project.rb
class Project
  include MongoMapper::Document
  
  key :name, String, :required => true
  key :priority, Integer
  
  many :tasks
end

# models/task.rb
class Task
  include MongoMapper::Document
  
  key :project_id, ObjectId
  key :name, String
  key :completed, Boolean
  
  belongs_to :project
end

# script/console
Project.all
Project.all(:order => "name")
Project.all(:priority => 3)
Project.all(:priority.gte => 2)
Project.all(:priority.in => [2, 3])
<!-- projects/_form.html.erb -->
<p>
  <%= f.label :priority %><br />
  <%= f.select :priority, [1,2,3,4,5] %>
</p>

<!-- tasks/_form.html.erb -->
<p>
  <%= f.label :project_id %><br />
  <%= f.collection_select :project_id, Project.all, :id, :name %>
</p>

RSS Feed for Episode Comments 38 comments

1. Michael Dec 28, 2009 at 03:04

Awesome cast! Thanks!


2. mikhailov Dec 28, 2009 at 03:07

it's really useful
Thank you, Ryan!


3. Levy Carneiro Jr Dec 28, 2009 at 03:09

Great screencast, Ryan!

It's worth noting that this example only shows a normal table to table relationship. In "mongoDBland" this is called a *db reference*, there is, a reference between 2 collections.

There's this simple relationship between tables (actually collections in mongoDB), and there's the new thing which is embedded documents. To embeded the Task model inside a Project, in this example, you have to change the file "app/models/task":

# models/task.rb
class Task
  include MongoMapper::EmbeddedDocument
...

That's it.

And to those asking "Should I embeded or reference?", read more this subject at:

http://www.mongodb.org/display/DOCS/Schema+Design#SchemaDesign-Embedvs.Reference

Cheers!
Levy


4. Michael van Rooijen Dec 28, 2009 at 03:13

Very nice Ryan!
I only looked into MongoDB itself for a few but never tried to do anything with it in Rails. That MongoMapper Gem seems to work very well! I will definitely give it a shot!

Thanks.


5. Nithin Bekal Dec 28, 2009 at 03:24

Was hoping for a railscast to help me get started with MongoDB. Thanks! :)


6. Alican Dec 28, 2009 at 03:49

Thank you, great cast as always.


7. Mantas Dec 28, 2009 at 04:21

Any ideas how to handle authentication with mongomapper? Does authlogic work with it?


8. Mereghost Dec 28, 2009 at 07:25

@Mantas:

Devise should work with it. I'm not sure about Authlogic although.


9. Jay Shepherd Dec 28, 2009 at 07:37

Just a quick note that there is a MongoDB hosting service called MongoHQ.

http://www.mongohq.com


10. Ryan Bates Dec 28, 2009 at 08:50

@Levy, great points. Here I wanted to show what Rails developers are most familiar with to get started. I hope to make a more advanced episode in the future where I show some of the things that make MongoDB more unique (most were touched on in that blog post).

@Mantas, that's a great question. AFAIK Authlogic still does not support MongoMapper however there is an open ticket on it.

http://github.com/binarylogic/authlogic/issues#issue/15

There are many plugins I would like to see support MongoMapper. I encourage them to build in an adapter to deal with the different databases.


11. Paul Gatt Dec 28, 2009 at 09:58

Devise does work with Mongo, I've been playing with it this week.

What I would love is a railscast on gridfs. I'm fairly new to rails and I got Devise to work with mongo and mongomapper, but gridfs is confusing me no end.


12. Shreyans Dec 28, 2009 at 10:18

Good to know about MongoDB. I have a question though. Where is the data stored in mongodb? Is there any way to perform full text search and db backups, etc like traditional relational databases would allow us to do?
Also how is it different from storing data in xml files?


13. Cascadeclimbers Dec 28, 2009 at 11:10

Ryan great screencasts!

What are the advantages of using mongodb over couchdb?


14. Thibaud Guillaume-Gentil Dec 28, 2009 at 12:11

@paul gatt for mongodb and gridfs there is the new CarrierWave gem: http://github.com/jnicklas/carrierwave


15. Fredrik Dec 28, 2009 at 12:52

There's also http://github.com/twoism/grip for gridFs.

RailsTips got an article released a few days ago about it -> http://railstips.org/2009/12/23/getting-a-grip-on-gridfs


16. Ernest Dec 28, 2009 at 18:05

How about performance (for example vs mysql)?


17. Paul Gatt Dec 28, 2009 at 20:37

Thibaud and Fredrik, tried all those options.

I may just not know enough, but I couldn't get them to work. Saved the image to mongo, but couldn't pull it back out for love or money.


18. mikhailov Dec 28, 2009 at 22:06

Ryan, what's reason for usage of "h" escape_html method within Rails 2.3.5?
By the way, MongoDB’s performance as compared to others
http://prajwal-tuladhar.net.np/2009/11/15/500/mongodbs-performance-as-compared-to-others-esp-couchdb/


19. Eric Berry Dec 28, 2009 at 22:12

Great screencast Ryan!

I just wanted to mention that there was also a screencast series recently done on MongoDB by Joon You (rubyhead) which can be found on http://teachmetocode.com.

Apologies for the shameless plug ;-)


20. raj Dec 29, 2009 at 01:40

Thanks a LOT for feeding us Awesome screencast! I can't wait for the next screencast that explains more advanced mongo mapper like callback, how to tackle many to many relation, and probably if there is any asynchronous way for mongodb using ruby.

Where is the clap of your finger?? I was expecting it !


21. Fredrik Dec 29, 2009 at 02:11

@Paul

You need a Rack or Metal-library that can handle the serving on the view-side.

http://github.com/twoism/metal_grid_fs/

For example :)


22. Fredrik Dec 29, 2009 at 02:51

@Paul

There's also a faster, but not equally flexible way of doing it.

http://fukamachi.org/wp/2009/11/20/rails-metal-mongodb-gridfs-access/

Code needs editing on the parts of what database it uses.


23. Mislav Dec 29, 2009 at 04:30

Script to install MongoDB on OS X using Homebrew and set it to automatically run: http://gist.github.com/265272

One note about the screencast: Tasks should have been embedded in the Projects collections, because a single task isn't shared among projects. This is the true Mongo way. MongoMapper supports embedded models in a very nice object-oriented way.


24. David Westeirnk Dec 29, 2009 at 13:35

Hi Ryan!

I saw this used with Rackamole (http://rackamole.com/) Maybe you can look into Rackamole too! It's a great rack plugin for monitoring a rails application.

I'm not used to this kind of DBM, I mostly use SQL (MySQL and MSSQL) so I can't really see the big avantages of this kind of DBM...


25. Randuin Dec 29, 2009 at 21:33

How's the performance of MongoDB? Especially when it comes to fulltext searching?


26. mrbrdo Dec 30, 2009 at 16:01

I expected to hear some use cases for such databases. I don't suppose they perform as good as *SQL, and I guess they're only supposed to be used in certain situations? I found this was missing from the railscast.
Otherwise nice railscast.


27. Matthew Dec 30, 2009 at 18:44

Doesn't work for me. I can't create the scripts because of active record. How do I either turn off active record, or what do I put in databases.yml (currently it's blank) to make it stop wanting to connect to the db?


28. Fredrik Dec 31, 2009 at 02:31

@Matthew as long as you use Mongomapper in your models there shouldnt be any calls to ActiveRecord, and therefore no problems with configurations.


29. Shreyans Dec 31, 2009 at 06:26

How about if someone wants to visually change the data (I mean not from the console). Is that possible?


30. Fredrik Dec 31, 2009 at 14:50

@Shreyans

You got for Mac OS X - http://www.apple.com/downloads/macosx/development_tools/mongohub.html

Dunno if it works though, aint running Mac. MongoHub doesnt seem to work properly in Win7


31. freenight Jan 01, 2010 at 04:07

thanks Ryan.

by the way, which plugin do you use for the syntax highlighting??


32. Alex Jan 01, 2010 at 09:28

Ryan; Love your screencast on mongodb. I just wanted to add, for those users who use macports, there is a simpler way of installing mongodb and making sure it's up to date. Use the sudo port install mongodb command and you are all set to go with mongo!

Thanks Ryan, and Happy New Year!


33. EH Jan 03, 2010 at 23:37

Is it intentional (or my personal failing) that prevents me from being able to fast-forward and skip around your episodes when viewed in iTunes? The thumb is effectively disabled.


34. EH Jan 06, 2010 at 10:58

OK, it was of course my problem. The in-episode fast forward (at the bottom inside the frame) still does not work, but the iTunes scrubber (top, green window) does as always. Strange, but nevermind.


35. Boris Barroso Jan 07, 2010 at 06:04

There is a good and simple tutorial for isntalling mongodb, you wont need to compaile it
http://www.slideshare.net/scottmotte/mongodb-1825613


36. Christoph Jan 12, 2010 at 14:37

@Matthew: I have encountered the same problem. Running the console everything's fine but when trying to open the site in a browser passenger obviously tries to load ActiveRecord which then complains since no database is configured. After hours of trial and error I will give up on MongoMapper until it works fine.


37. Anton Jan 16, 2010 at 01:20

Love your casts Ryan. Any chance of getting one for integrating NEO4J with RoR?


38. Dom Jan 22, 2010 at 13:20

What does #{Rails.env} do?


39. Kristian Mandrup Jan 27, 2010 at 04:14

Seems like the page on how to install mongoDB on OS X and set it to autostart no longer works:(
I will try the Homebrew recipe from @Mislav instead ;)


40. Jeremy Chase Feb 19, 2010 at 04:29

I was working on a similar example using Rails3.Beta and MongoMapper. The biggest difficulty I had was that the models no longer inherited from ActiveRecord, and it felt like I had to change things significantly to make things work.

For example I couldn't use "form_for @object" because it would complain that @object didn't have method 'foo' (in this case I believe it was missing 'class_name'). I could get form_tag to work, but the experience made me wonder how well mongomapper+mongodb will work as a straight replacement to AR.

Well, I re-watched your cast and noticed that you didn't have these problems with 2.3.x!! Hopefully I am doing something wrong on my end, but am going to try with 2.3.x right now..

Very exciting though, I'm hoping to use Rails+mongo for my next side project, thank you for covering it here.


41. Jeremy Chase Feb 19, 2010 at 08:39

A little followup: I went back and tried this with Rails 2.3.5 and everything worked much better. I did have problems with the generator scripts; it seems like they aren't too tolerant of other ORM's. Once I got everything laid out though it worked brilliantly.

I did have problems with my database.yml file though; In your cast you don't empty it, but if I left database.yml populated with the sqlite information it would barf when I started the server. An empty database.yml made things much better.


42. David Feb 21, 2010 at 13:08

Is there support for has_many :through situations?


43. discount links of london Feb 27, 2010 at 00:56

Thank you for the valuable information. I have used most of these. Keep up the good work.


44. aust_rails_developer Feb 28, 2010 at 20:31

If you are having trouble with your app being unable to start because of activerecord/database.yml related errors, make sure to put this

config.frameworks -= [ :active_record]

in your environment.rb


45. Andrew Apr 27, 2010 at 15:18

Thank you, very helpful. I'd like to review a similar cast about Cassandra with Rails.


46. bocek ilaclama May 27, 2010 at 07:51

thank


47. hulu downloader May 31, 2010 at 19:28

whole idea that complex software should "help" me doing things


48. dicount air max shoes Jun 18, 2010 at 18:48

thank you for your nice post...


49. Blackberry Series Jul 19, 2010 at 00:06

"iPhone is a revolutionary, incredible products on the market, more than any other mobile phone for five years," lead apple chief executive Steve jobs, "finger said. Let's Enjoy 10 the Most Popular e66 white as Gifts for Successful Career Women This Year" we are born, and the ultimate designated equipment using created the iPhone since the mouse is the most innovative user interface.


50. jogos gratis Jul 19, 2010 at 01:48

I was actually looking for this resource a few weeks back. Thanks for sharing with us your wisdom.This will absolutely going to help me in my projects .


51. fm transmitter Jul 28, 2010 at 22:50

How about performance (for example vs mysql)?


54. fadewatches Aug 06, 2010 at 17:42

I am a fanatic watch collection, especially the well-known watches, you also can do, just click on my name!!!!!!!!


54. fashion uggs Aug 08, 2010 at 01:12

Your blog appears quite informative. I liked it. So much useful material. I read with great interest.Can you please tell me how can I read your rss blog?


54. discount uggs Aug 08, 2010 at 01:24

There is one more site that I have visited, provide me information that is really unique and the service that they offer also I have experienced, really I enjoy this sevice so I request others please visite this and I want to tell you that after enjoying this service you’ll enjoy it again and again its .


55. UGG Boots on sale Aug 10, 2010 at 18:55

Gooooooooooooooooooood luck ~~!!


56. Cheap Green Bay Packers Tickets Aug 12, 2010 at 04:02

One note about the screencast: Tasks should have been embedded in the Projects collections, because a single task isn't shared among projects. This is the true Mongo way. MongoMapper supports embedded models in a very nice object-oriented way.


57. Sai Perchard Aug 15, 2010 at 09:11

If I attempt to use any generators (e.g. nifty_scaffold or scaffold) the following error is thrown:

uninitialized constant Rails::Generator::GeneratedAttribute::ActiveRecord

I have turned off active record in environment.rb via:

config.frameworks -= [:active_record]

My database.yml file is empty. Everything is configured as per the screencast/mongo docs.

I'm running Rails 2.3.8, mongo 1.0.7, mongo_mapper 0.8.3, and MongoDB 1.6.0.

If anybody else has run in to this error (and found a solution), please comment. Previous comments have alluded to similar problems.

The files could be created manually, however I'm interested as to why this is happening - active record should be disabled.


58. cheapgucciboots Aug 16, 2010 at 02:07

thane


59. cheap jerseys Aug 16, 2010 at 17:22

Thanks for such a great post and the review, I am totally impressed! Keep stuff like this coming.


60. Wholesale baseball hats Aug 20, 2010 at 20:16

Generally I do not post on blogs, but I would like to say that this post really forced me to do so, Excellent post!


61. converse all star Aug 20, 2010 at 20:57

love converse all star,love yourself.High quality low price.It's fit for you.


62. authentic nike shoes Aug 23, 2010 at 22:52

Good job! very good cord.This is all very new to me and this article really opened my eyes. thank you


63. clothes store Aug 24, 2010 at 19:32

Hi, interesting post. I have been pondering this topic,so thanks for writing. I'll probably be coming back to your blog. ...


64. PDF to Images Converter Aug 24, 2010 at 22:57

Some times, to a certain need, we have to convert PDF to image for enjoyment.


65. Wholesale Electronics Aug 25, 2010 at 01:18

Discount Wholesale Electronics, Wholesale Cell Phones, Electronic Gadgets and More from the Best Dropship Wholesaler


66. louis vuitton shoes Aug 26, 2010 at 23:19

Thanks for sharing your article. I really enjoyed it. I put a link to my site to here so other people can read it. My readers have about the same interets


67. snow boots Aug 30, 2010 at 20:37

It's worth noting that this example only shows a normal table to table relationship.


68. louis vuitton sunglasses Sep 01, 2010 at 21:39

I think this is a great post. One thing that I find the most helpful is number five. Sometimes when I write, I just let the flow of the words and information come out so much that I loose the purpose. It’s only after editing when I realize what I’ve done. There’s defiantly a lot of great tips here I’m going to try to be more aware of.

Add your comment:

(SKIP THIS ONE)

(required)

(not shown)


(use pastie or gist for code)

sponsored by:
if you want to help:
required:
Get Quicktime Player
Give Back to Open Source