我想分析Mongo中托管的数据库。因此,我想将mongo URI连接到熊猫,以便可以在Jupyter Lab环境中自由运行所有python查询。
今天这是我的mongo连接:
“ mongoURI”:“ mongodb + srv:// test:test12345@cluster0-ze0tw.mongodb.net/databasetest?retryWrites = true&w = majority”
我已经阅读了其他答案,他们共享了这段代码,据说可以帮助我解决此连接。如果填写正确,我不太满意。你们能以上面显示的连接为例向我介绍一下。
import pandas as pd
from pymongo import MongoClient
def _connect_mongo(host, port, username, password, db):
""" A util for making a connection to mongo """
if username and password:
mongo_uri = 'mongodb://%s:%s@%s:%s/%s' % (username, password, host, port, db)
conn = MongoClient(mongo_uri)
else:
conn = MongoClient(host, port)
return conn[db]
def read_mongo(db, collection, query={}, host='localhost', port=27017,
username=None, password=None, no_id=True):
""" Read from Mongo and Store into DataFrame """
# Connect to MongoDB
db = _connect_mongo(host=host, port=port, username=username, password=password,
db=db)
# Make a query to the specific DB and Collection
cursor = db[collection].find(query)
# Expand the cursor and construct the DataFrame
df = pd.DataFrame(list(cursor))
# Delete the _id
if no_id:
del df['_id']
return df
答案 0 :(得分:0)
似乎正在连接到MongoDB Atlas实例。首先检查您的Python客户端计算机的IP是否在Atlas IP Whitelist(安全性->网络访问-> IP白名单)中。