Skip to content

Instantly share code, notes, and snippets.

@raydive
Created January 21, 2014 17:27
Show Gist options
  • Select an option

  • Save raydive/8544292 to your computer and use it in GitHub Desktop.

Select an option

Save raydive/8544292 to your computer and use it in GitHub Desktop.

Ruby ToolboxからMongoDB関連のgemを見る

The Ruby ToolboxのMongoDB Clientsから動きが活発そうなものを調べてみる。

MongoDB

  • ドキュメント指向データベースの一つ
  • RDBライクな検索クエリ
  • スキーマレス
    • 任意のフィールドを好きなときに追加できる
  • レプリケーション、オートフェイルオーバー、レンジパーティション、バランシング機能あり
  • Read/Writeの性能は高い
  • 好きなプログラム言語からアクセスできるAPIや、RESTインターフェースあり
  • 性能関連はこのへん見ると分かる
  • MongoDBが適さないものとか

Mongoid

  • MongoidはMongoDBのObject-Document-Mapper(ODM)
  • 現在のバージョンは3系統がメイン、4.0.0alpha2が最近出た
  • 大体の使い方はsample.rbみたいな感じ
class Artist
  include Mongoid::Document
  field :name, type: String
  embeds_many :instruments
end

class Instrument
  include Mongoid::Document
  field :name, type: String
  embedded_in :artist
end

syd = Artist.where(name: "Syd Vicious").between(age: 18..25).first
syd.instruments.create(name: "Bass")
syd.with(database: "bands", session: "backup").save!
  • フィールドを定義して、関連をつくって
    • 関連はembeds_~で作られるものと、ActiveRecordでお馴染みのhas_one、has_manyなどリレーショナルな関連がある

Mongo Ruby Driver

  • MongoDBの本家で作ってる(?)
  • ドキュメント読むと、対応するRubyのバージョンが1.8.7と1.9.3となっているので若干古いかな
    • と思ったらGithubのほうは2.0.0に言及してましたね
  • Githubから引っ張ってきたサンプルコードを見ると、Mongoidと違って、MongoDBを操作するというイメージかな
require 'mongo'

# connecting to the database
client = Mongo::Client.new # defaults to localhost:27017
db     = client['example-db']
coll   = db['example-collection']

# inserting documents
10.times { |i| coll.insert({ :count => i+1 }) }

# finding documents
puts "There are #{coll.count} total documents. Here they are:"
coll.find.each { |doc| puts doc.inspect }

# updating documents
coll.update({ :count => 5 }, { :count => 'foobar' })

# removing documents
coll.remove({ :count => 8 })
coll.remove

比べてみると

  • Mongoidのほうが抽象度は高く、ActiveRecord使ってる人ならわかりやすい
  • Ruby Driverは生のAPIをRubyから触れるようにしました、というイメージが否めない
  • 開発のアクティブさやRubyで使うなら……ということを考えるとMongoidのほうがよさそうでした
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment