---
title: "[转]Ruby连接MongoDB"
author: "blueheart2008"
date: "2012-12-24T10:52:14Z"
tags: []
categories: ["编程语言"]
slug: "ruby-mongodb"
draft: false
lastmod: "2012-12-24T10:52:14Z"
id: 1752890
url: "https://blueheart2008.iteye.com/blog/1752890"
---

# Ruby连接MongoDB

想要在Ruby中连接MongoDB，需要使用mongo模块，该模块可以通过ruby自带的gems程序进行安装。

```
$ gem update --system
$ gem install mongo
$ gem install bson_ext
```

Mongo模块提供了Mongo::Connnection类连接MongoDB，如果不指定具体的数据库，默认情况下会创建一个持有MongoDB连接的实例，

```
require 'mongo'
conn = Mongo::Connection.new
puts conn.class            # Mongo::Connection
puts conn.database_names   # ["admin", "local", ...]
```

如果需要指定默认的数据库，可以在创建实例的时候指定。如果指定的数据库不存在，MongoDB会创建该数据库。

```
db = Mongo::Connection.new.db('blog')
db.create_collection('users')  # 创建一个collection
puts db.class                  # Mongo::DB
```

涉及数据库的操作，基本的创建、删除、拷贝、重命名。重命名操作可以通过拷贝和删除组合完成。

```
conn.copy_database('blog', 'blog-backup')
conn.drop_database('blog-backup')
```

在MongoDB中没有了表的概念，取而代之的是collection，可以理解为容器，记录全都存放在collection中。对collection所能做的也是传统的CRUD操作，不过使用起来更加面向对象。Mongo模块的Collection类提供了insert, drop, update, find等方法操作collection。下面大概地了解一下它们的用法。

在先前创建的名为users的collection中插入几条记录。MongoDB中记录的类型为类JSON格式，形式如下。

```
{ 
  "_id" : ObjectId("4d51eb216b6f45122c000001"), 
  "username" : "clovery", 
  "password" : "clovery" 
}
# ruby中无法识别json格式，所以插入记录时使用ruby的hash格式，mongo模块会自动转换成json形式
# 向users中插入三条记录
db['users'].insert({"username" => "andy", "password" => "12345"})
db['users'].insert({"username" => "alien", "password" => "12345"})
db['users'].insert({"username" => "angel", "password" => "12345"})

db['users'].count  # 3
```

可以通过find\_one和find检索记录。find\_one返回一个BSON::OrderedHash数据，类似于ruby的hash类型。find返回Mongo::Cursor引用，可以 对其进行迭代检索所有符合条件的数据。

```
db['users'].find_one   
# {"_id"=>BSON::ObjectId('4d5246c26b6f451714000004'), "username"=>"andy", "password"=>"12345"}

db['users'].find.each do |row|
  print "#{row['username']} "
end
# andy alien angel
```

update可以更新原有的记录。

```
db['users'].update({'username' => 'andy'}, {'$set' => {'password' => 'andy'}})
# {"_id"=>BSON::ObjectId('4d52499d6b6f451714000008'), "password"=>"andy", "username"=>"andy"}
```

使用remove删除collection中的记录，如果不指定条件，会删除collection中的所有记录。

```
db['users'].remove({'username' => 'andy'}) 
db['users'].count # 2
```

删除collection

```
db.drop_collection('users')
```

关于Ruby如何连接MongDB，详细信息请参考[MongoDB Ruby Driver Tutorial](http://api.mongodb.org/ruby/current/file.TUTORIAL.html)。