LoginSignup
4
4

More than 5 years have passed since last update.

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

Posted at

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みたいな感じ
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を操作するというイメージかな
sample.rb
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のほうがよさそうでした
4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4