ruby 操作MongoDB

想要在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]])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值