文档菜单
文档首页
/ / /
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

<connection string 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社区论坛寻求帮助或使用页面右侧或右下角的评分此页选项卡提交反馈。

返回

创建连接字符串