1.21 jigowatts

Great Scott!

Ruby MongoDBに接続する

概要

MongoDBをインストールしてから半年ほど経過してしまいましたが、また少しずつ進めていきます。

MongoDBのシェアはDB-Enginesによると(2016/8現在)データベース全体で4位、NoSQLでは1位のようです。それでも上位3つのデータベースは桁違いですが、PostgreSQLと同じくらいのシェアがあるんですね。仕事で使っていなくても、この結果だけで少し触って遊んでみる理由には十分じゃないでしょうか。

f:id:sh_yoshida:20160821161708p:plain
DB-Engines Ranking - popularity ranking of database management systems

環境

OS: CentOS 7
Ruby: 2.3.1
MongoDB: 3.2

ドライバのインストール

RubyGems(パッケージマネージャ)よりMongoDBのRubyドライバをインストールします。

$ gem install mongo

接続

tutorialデータベースに接続してusersコレクションの取得を行います。

require 'rubygems'
require 'mongo'

# MongoDBへ接続
client = Mongo::Client.new('mongodb://localhost/tutorial')
collection = client[:users]

以下の方法でも接続できます。私はURIを指定が気に入ってますがこの辺はお好みで。

client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'tutorial')

登録

# 10回ループ回して、1件毎にコレクションの登録
10.times{|i|
  doc = {name: 'Alice_' + i.to_s, num: i}
  collection.insert_one(doc)
}

# まとめて登録
docs = [
  {name: 'John', country: 'Canada'},
  {name: 'Smith', country: 'USA'}
]
result = collection.insert_many(docs)
puts result.inserted_count

取得

# コレクションのカウント
puts collection.count

# データ取得
result = collection.find()

result.each do |doc|
  puts doc
end

更新

# コレクションの更新
collection.update_one({name: 'Alice_4'},{'$set': {age: 18}})

# まとめて更新
result = collection.update_many({num: {'$gte': 7}}, {'$set': {country: 'England'}})
puts result.modified_count

削除

# コレクションの削除
collection.delete_one(name: 'Smith')
puts collection.count

# まとめて削除
result = collection.delete_many()
puts result.deleted_count

sh-yoshida.hatenablog.com
sh-yoshida.hatenablog.com
sh-yoshida.hatenablog.com

参考

https://docs.mongodb.com/ruby-driver/master/

MongoDBイン・アクション

MongoDBイン・アクション

RDB技術者のためのNoSQLガイド

RDB技術者のためのNoSQLガイド