MongoMapper Embeddable

Because MongoDB doesn't have joins but does have the ability to embed documents in other documents, it is often the case that for query minimization purposes it is useful to provide a few key properties of a document when it's embedded in another one. MongoMapper Embeddable is a plugin for MongoMapper to do just that.


gem install mm-embeddable


To declare an embeddable version of a MongoMapper document, simply call embeds after all of your key declarations and specify the keys that should be embedded in the “compacted” version of the model. This will automatically generate a YourDocumentClass::Embeddable class that can be embedded in other documents.


require 'mongo_mapper'
require 'mm-embeddable'

class User
  include MongoMapper::Document

  key :name, String
  key :profile_photo, String
  key :bio, String
  key :interests, Array

  embeds :name, :profile_photo

class Post
  include MongoMapper::Document

  key :author, User::Embeddable
  key :title, String
  key :body, String

This creates an embeddable version of the User model that only contains the name and profile picture. If that's all I access, then no additional queries are called. Example:

<h1><%= @post.title %></h1>
<span class='author'>
  <img src='<%= %>'/> <%= %>
<div class='body'><%= @post.body %></div>

But if we need other attributes that haven't been stored in the embeddable model, we can do so seamlessly:

# no additional query is performed
# the full document is seamlessly fetched in the background

In this way we take full advantage of Mongo's embedded documents while still being able to easily fall back to the full document when necessary.

Note on Patches/Pull Requests

  • Fork the project.

  • Make your feature addition or bug fix.

  • Add tests for it. This is important so I don't break it in a future version unintentionally.

  • Commit, do not mess with rakefile, version, or history. (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)

  • Send me a pull request. Bonus points for topic branches.

Copyright © 2010 Michael Bleigh. See LICENSE for details.