您的位置:首页 > 其它

文章标题

2016-03-23 11:47 591 查看
需要的环境:

安装: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


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: