连接到MongoDB
1
创建您的PyMongo应用程序
将以下代码复制并粘贴到您的应用程序中的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>
占位符替换为您从本指南中的“创建连接字符串”步骤复制的连接字符串。创建连接字符串
完成这些步骤后,您将拥有一个可以正常工作的应用程序,该程序使用驱动程序连接到您的MongoDB部署,对示例数据运行查询,并打印结果。
注意
如果在这一步遇到问题,请在MongoDB社区论坛寻求帮助或使用页面右侧或右下角的评分此页选项卡提交反馈。