Chinaunix首页 | 论坛 | 博客
  • 博客访问: 189553
  • 博文数量: 29
  • 博客积分: 731
  • 博客等级: 上士
  • 技术积分: 435
  • 用 户 组: 普通用户
  • 注册时间: 2010-12-06 16:18
文章分类

全部博文(29)

文章存档

2012年(29)

分类: Python/Ruby

2012-06-04 18:57:31

想要在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]])
 
阅读(3385) | 评论(0) | 转发(0) |
0

上一篇:ruby gem常用命令

下一篇:此博客已改地址

给主人留下些什么吧!~~