Reputation: 1245
I have created an account with Atlas and now I am trying to retrieve some information from the database. My native language is R, so I inserted the "iris" data set into the collection called "table". To show that there is data in my new database "test", I use the mongolite command (this is the R pymongo):
#m is my client connection
m$count()
[1]5490
The problem is connecting with python. I am currently on Jupyter Notebook. Here is the code.
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
When I call any methods on the database I get the error.
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
I would like to be able to connect and start exploring the data in my "test" data set by using methods like, list_database_names(), list_collection_names() etc.. Thank you kindly
Upvotes: 2
Views: 13276
Reputation: 335
Try this: I am using a python kernel in a jupyter notebook though but the logic remains the same
from pymongo import MongoClient
# replace "USER" and "PASSWORD" with your user and password respectively.
client = MongoClient("mongodb+srv://USER:[email protected]/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)
Upvotes: 1
Reputation: 121
To connect to mongodb using python from any editor
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["pyramids"] #pyramids is the database
mycol = mydb["invoices"] #invoice is the collection
Upvotes: 0