需要的环境:
安装:mongodb
gem包: mongo(ruby driver)
require 'mongo'
Mongo::Logger.logger.level = ::Logger::FATAL (去掉控制台的log)
#连接mongodb,选择一个数据库(可以不存在,在插入数据之后,可以在库中show dbs 看到被创建的db)
db = Mongo::Client.new(["localhost:27017"],:database=>"runoob")
#创建一个索引col并插入一条数据 要用json的数据形式
res = db["col"].insert_one({title: 'MongoDB 教程',
description: 'MongoDB 是一个 Nosql 数据库',
by: '菜鸟教程',
url: 'http://www.runoob.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100
})
res = db["col"] #选择新建的索引col
res.find.each do |x| #find方法可以返回索引中的文档
puts x["title"]
end
#创建一个索引artists,并插入多条数据,json的数据形式
res = db[:artists].insert_many([
{title:'art1',content:"today is a good day 1",create_at:Time.now.strftime("%F %T")},
{title:'art2',content:"today is a good day 2",create_at:Time.now.strftime("%F %T")},
{title:'art3',content:"today is a good day 3",create_at:Time.now.strftime("%F %T")},
{title:'art4',content:"today is a good day 4",create_at:Time.now.strftime("%F %T")},
{title:'art5',content:"today is a good day 5",create_at:Time.now.strftime("%F %T")},
{title:'art6',content:"today is a good day 6",create_at:Time.now.strftime("%F %T")},
])
res = db[:artists].find.each do |x|
puts x["content"]
end