首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > 其他数据库 >

[转]Ruby联接MongoDB

2013-01-05 
[转]Ruby连接MongoDBRuby连接MongoDB想要在Ruby中连接MongoDB,需要使用mongo模块,该模块可以通过ruby自带

[转]Ruby连接MongoDB

Ruby连接MongoDB

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

可以通过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。

热点排行