文档菜单

文档首页开发应用程序Python 驱动程序PyMongo

连接到 MongoDB

1

将以下代码复制并粘贴到quickstart.py 文件中

from pymongo import MongoClient
uri = "<connection string URI>"
client = MongoClient(uri)
try:
database = client.get_database("sample_mflix")
movies = database.get_collection("movies")
# Query for a movie that has the title 'Back to the Future'
query = { "title": "Back to the Future" }
movie = movies.find_one(query)
print(movie)
client.close()
except Exception as e:
raise Exception("Unable to find the document due to the following error: ", e)
2

<连接字符串 URI> 占位符替换为从本指南的“创建连接字符串”步骤中复制的连接字符串。

3

在您的 shell 中,运行以下命令以启动此应用程序

python3 quickstart.py

输出包括检索到的电影文档的详细信息

{
_id: ...,
plot: 'A young man is accidentally sent 30 years into the past...',
genres: [ 'Adventure', 'Comedy', 'Sci-Fi' ],
...
title: 'Back to the Future',
...
}

提示

如果您遇到错误或没有输出,请检查您是否指定了正确的连接字符串,并且是否加载了示例数据。

完成这些步骤后,您将拥有一个可工作的应用程序,该应用程序使用驱动程序连接到您的 MongoDB 部署,对示例数据运行查询,并打印出结果。

注意

如果您在此步骤中遇到问题,请在MongoDB 社区论坛 中寻求帮助或使用右侧或右下角的评价此页面 标签提交反馈。

下一步
← 创建连接字符串