Docs 菜单
Docs 主页
/ / /
Ruby 驱动程序
/

连接至 MongoDB

1

导航到quickstart.rb 目录中的ruby-quickstart 文件。将以下代码复制并粘贴到本教程 下载和安装步骤中的 Bundler 代码下方。此代码连接到MongoDB并查询movies sample_mflix数据库中的 集合。

uri = '<connection string>'
begin
client = Mongo::Client.new(uri)
database = client.use('sample_mflix')
movies = database[:movies]
# Queries for a movie that has the title 'Back to the Future'
query = { title: 'Back to the Future' }
movie = movies.find(query).first
# Prints the movie document
puts movie
ensure
client&.close
end
2

<connection string> 占位符替换为从本教程的“创建连接字符串”步骤中复制的连接字符串。

3

ruby-quickstart目录中,运行以下Shell命令以运行应用程序:

ruby quickstart.rb

命令行输出包含有关检索到的电影文档的详细信息:

{"_id"=>BSON::ObjectId('...'), "plot"=>"A young man is accidentally sent
30 years into the past in a time-traveling DeLorean invented by his friend,
Dr. Emmett Brown, and must make sure his high-school-age parents unite
in order to save his own existence.", ...
"title"=>"Back to the Future", ...

如果遇到错误或看不到输出,请确保在 quickstart.rb文件中指定了正确的连接字符串并加载了示例数据。

完成这些步骤后,您有一个正常运行的应用程序,它使用驱动程序连接到 MongoDB 部署、对示例数据运行查询并打印结果。

注意

如果您在此步骤中运行问题,请在 MongoDB Community论坛中寻求帮助,或使用此页面右侧的 Rate this page标签页提交反馈。

后退

创建连接字符串