Docs 菜单
Docs 主页
/ / /
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',
...
}

提示

如果遇到错误或看不到输出,请检查是否指定了正确的连接string ,以及是否加载了示例数据。

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

注意

如果在该步骤中遇到问题,请在 MongoDB 社区论坛中寻求帮助,或使用本页面右侧或右下方的 Rate this page(本页内容评级)标签页提交反馈。

后退

创建连接字符串

来年

后续步骤