安装MongoDB库
pip install pymongo
python 代码
'''
Author: tkhywang 2810248865@qq.com
Date: 2023-08-21 10:22:30
LastEditors: tkhywang 2810248865@qq.com
LastEditTime: 2023-08-21 11:17:45
FilePath: \PythonProject02\MongoDB 数据库.py
Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
'''
from pymongo import MongoClient
# 连接数据库
#地址和端口连接
client = MongoClient(host='192.168.56.22', port=27017, username='admin', password='admin123')
# 获取数据库和集合
#db = client['database_name']
#collection = db['collection_name']
db = client['my_db1']
#collection = db['collection_name']
collection = db['mycol3']
# 查询数据
for document in collection.find():
print(document)
# 关闭连接
client.close()
连接成功输出结果