インストール

   1  % gem install mongo_mapper

mongomapper (古いバージョンのgem)も存在するので注意

セットアップ

   1  require 'mongo_mapper'
   2  MongoMapper.database = "app1"  # DB名

  • 各モデル内で明示されない場合に利用されるデフォルトのDB名

モデル

   1  class Player
   2    include MongoMapper::Document
   3    key :name,   String, :required => true
   4    key :policy, Integer
   5    key :renkei, String
   6    key :note,   String
   7    timestamps!
   8  
   9    validates_uniqueness_of :name
  10  end

  • pkeyのidが勝手に定義される
  • 文字列は長さに制限がないので全てString

検索

   1  Player.count
   2  => 822
   3  
   4  Player.count(:renkei=>'萩原型')
   5  => 135
   6  
   7  Player.first
   8  => #<Player label: "萩原 忠志" ... >
   9  
  10  Player.all(:label=>/^河本/).map{|p| [p.pos, p.label]}
  11  => [["FW", "河本 鬼茂"], ["GK", "河本 龍将"]]

高度な設定

  • ARで言うテーブルをMongoDBではコレクションと呼ぶ
  • table を collection に変えるだけでAR風のAPIが使える

   1  class Pref
   2    include MongoMapper::Document
   3  
   4    set_database_name "usei"  # app1でなく usei DBを利用
   5    set_collection_name "zip" # prefs でなく zip コレクションを利用
   6  ...

長所

  • MongoDB自体の性能がよい
  • インタフェースが AR と DM のよい点を取り込み (CRUDはAR, SearchはDM)
  • バリデーションや関連もサポート
  • 正規表現による検索

短所

  • サーバ(MongoDB)への再接続などのコネクション機能が弱い(mongo_mapper でなく mongo の問題かも)
posted by Png maiha on Sun 21 Feb 2010 at 16:51
Contents
[NoSQL] MongoMapper (MongoDB用のORM) の使い方
Comments
瀧内元気: MacOS版は以下にあります * [genki/ViMouse](https://githu... '23-1
KingofSmack: Here also good reads for this mobile applicatio... '14-5
Spencer: You don't have to re-compile it, this version w... '14-4
staiano: Any chance we can get a recompile for 10.9? '14-1
dsjf: https://gist.github.com/6bf1bf2c3cbb5eb6e7a7 これ... '13-1
Services from s21g
twpro(ツイプロ)
Twitterプロフィールを快適検索
地価2009
土地の値段を調べてみよう
MyRestaurant
自分だけのレストラン手帳
Formula
ブログに数式を埋め込める数式コミュニティ