【问题标题】:Connecting to MongoDB using PyMongo on Jupyter notebook在 Jupyter 笔记本上使用 PyMongo 连接到 MongoDB
【发布时间】:2019-02-24 19:52:52
【问题描述】:

我已经在 Atlas 上创建了一个帐户,现在我正在尝试从数据库中检索一些信息。我的母语是 R,所以我将“iris”数据集插入到名为“table”的集合中。 为了显示我的新数据库“test”中有数据,我使用了 mongolite 命令(这是 R pymongo):

#m is my client connection
m$count()
[1]5490

问题在于与 python 连接。我目前在 Jupyter Notebook 上。这是代码。

import pymongo as pm
import pprint
import requests

url= "mongodb://jordan:*************@jordandb-shard-00-00-ykcna.mongodb.net:27017,jordandb-shard-00-01-ykcna.mongodb.net:27017,jordandb-shard-00-02-ykcna.mongodb.net:27017/test?ssl=true&replicaSet=JordanDB-shard-0&authSource=admin&retryWrites=true"

client = pm.MongoClient(url)
print(client)
[out]Database(MongoClient(host=['jordandb-shard-00-02-ykcna.mongodb.net:27017', 'jordandb-shard-00-01-ykcna.mongodb.net:27017', 'jordandb-shard-00-00-ykcna.mongodb.net:27017'], document_class=dict, tz_aware=False, connect=True, ssl=True, replicaset='JordanDB-shard-0', authsource='admin', retrywrites=True), 'test')
#I am assuming this means I am connected

当我调用数据库上的任何方法时,我得到了错误。

db = client.test #test is name of collection
db.iris.find_one({})

ServerSelectionTimeoutError               Traceback (most recent call last)
<ipython-input-15-ab74ef5f0195> in <module>()
----> 1 db.iris.find_one({})

/opt/conda/lib/python3.6/site-packages/pymongo/collection.py in find_one(self, filter, *args, **kwargs)
   1260 
   1261         cursor = self.find(filter, *args, **kwargs)
-> 1262         for result in cursor.limit(-1):
   1263             return result
   1264         return None

我希望能够使用 list_database_names()、list_collection_names() 等方法连接并开始探索我的“测试”数据集中的数据。谢谢您

【问题讨论】:

  • 您找到解决方案了吗?因为我也面临同样的问题

标签: python mongodb jupyter-notebook pymongo mongodb-atlas


【解决方案1】:

试试这个:虽然我在 jupyter notebook 中使用 python 内核,但逻辑保持不变

from pymongo import MongoClient
# replace "USER" and "PASSWORD" with your user and password respectively.
client = MongoClient("mongodb+srv://USER:PASSWORD@cluster0-hhhbr.mongodb.net/test?retryWrites=true&w=majority")

# replace "local" with any database in your cluster
db = client.local
# replace "emps" with your collection's name
collection = db.emps

# you can use the collection e.g, but this will return a cursor
collection.find()

# To get the actual data do this or create a context
# Don't forget to delete the 3 previous lines of codes if you are going to
# create a context
with client as cl:
    db = cl.local
    collection = db.emps
    for i in collection.find():
        print(i)

【讨论】:

    【解决方案2】:

    从任何编辑器使用 python 连接到 mongodb


    导入 pymongo

    myclient = pymongo.MongoClient("mongodb://localhost:27017/")
    mydb = myclient["pyramids"] #pyramids 是数据库
    mycol = mydb["invoices"] #invoice 是集合

    【讨论】:

      猜你喜欢
      • 2021-02-16
      • 2017-09-24
      • 2022-12-30
      • 2019-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-01
      相关资源
      最近更新 更多