[转]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 angelupdate可以更新原有的记录。
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。