欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用ruby操作MongoDB 博客分类: Database MongoDBRubyLinuxCouchDBrubygems 

程序员文章站 2024-03-15 13:36:41
...

MongoDB是基于文档、schema-free的、开源的数据库,可以操作JSON格式的数据和CouchDB类似。

http://www.mongodb.org/display/DOCS/Downloads 下载MongoDB

解压 mongodb-linux-i686-1.2.4.tgz

tar xvf mongodb-linux-i686-1.2.4.tgz
mv mongodb-linux-i686-1.2.4 mongodb

 创建一个目录来保存数据

cd mongodb
mkdir -p data/db

 运行mongodb

bin/mongod -dbpath data/db

 打开mongo的shell实验一下:

fuliang@fuliang-laptop ~/mongodb $ bin/mongo
MongoDB shell version: 1.2.4
url: test
connecting to: test
type "help" for help
> use mydb
switched to db mydb
> j = { name: "mongo"}
{ "name" : "mongo" }
> t = { x : 3 }
{ "x" : 3 }
> db.things.save(j);
> db.things.save(t);
> db.things.find();
{ "_id" : ObjectId("4b8e7da14290b1eee23e62f6"), "name" : "mongo" }
{ "_id" : ObjectId("4b8e7da94290b1eee23e62f7"), "x" : 3 }
> exit
bye

 安装ruby gem:

sudo gem install mongo
sudo gem install mongo_ex

 安装mongo_ex可以提高性能。

使用ruby 尝试一下mongodb的一些功能

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

相关资源:
       MongoDB的官方主页: http://www.mongodb.org/display/DOCS/Home
       MongoDB的一个指南: http://www.mongodb.org/display/DOCS/Ruby+Tutorial
       MongoDB的一个幻灯片: http://www.fuchaoqun.com/2010/01/mongodb-in-action/       
       MongoMapper的git官网: . http://github.com/jnunemaker/mongomapper
       MongoMapper的一个例子: http://railstips.org/blog/archives/2009/06/27/mongomapper-the-rad-mongo-wrapper/