1. 程式人生 > >ruby 操作MongoDB

ruby 操作MongoDB

#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]])