想要在Ruby中连接MongoDB,需要使用mongo模块,该模块可以通过ruby自带的gems程序进行安装。
$ gem update --system
$ gem install mongo
$ gem install bson_ext
简单的例子:
require 'mongo'
db = Mongo::Connection.new("localhost", 27017).db("dbname")
coll = db.collection("table")
my_doc = coll.find_one()
puts my_doc
example:
require 'rubygems' # not necessary for Ruby 1.9
require 'mongo'
#make a connection
db = Mongo::Connection.new.db("mydb")
#db = Mongo::Connection.new("localhost").db("mydb")
#db = Mongo::Connection.new("localhost", 27017).db("mydb")
#list all database
m = Mongo::Connection.new # (optional host/port args)
m.database_names.each { |name| puts name }
m.database_info.each { |info| puts info.inspect}
#drop database
m.drop_database('things')
#look at collections
db.collection_names.each { |name| puts name }
coll = db.collection("testCollection")
#insert a document
doc = {"name" => "MongoDB", "type" => "database", "count" => 1,
"info" => {"x" => 203, "y" => '102'}}
coll.insert(doc)
#find the first document
my_doc = coll.find_one()
p my_doc
#insert multiple documents
100.times { |i| coll.insert("i" => i) }
#count documents in a collection
puts coll.count()
#use cursor to get all document
coll.find().each { |row| p row }
#find documents with a query
coll.find("i" => 71).each { |row| p row }
coll.find("i" => {"$gt" => 50}).each { |row| p row }
coll.find("i" => {"$gt" => 20, "$lte" => 30}).each { |row| p row }
#query with regex
coll.find({"name" => /*.ongo.*/})
#create a index
coll.create_index("i")
# explicit "ascending"
coll.create_index([["i", ASCENDING]])
阅读(3426) | 评论(0) | 转发(0) |