简体   繁体   中英

Problems with connect to MongoDB Atlas from Python

I am new to MongoDB Atlas and Python. I am using Python 3.9 and PyMongo 4.0.1: I have trouble connecting to a free MongoDB Atlas cluster that I have created based on MongoDB instruction. Please see the attached image -- https://behainguyen.files.wordpress.com/2022/01/cloud-mongo-db-connection-string.jpg , my connection string is:

mongodb+srv://behai:<password>@cluster0.71o6u.mongodb.net/myFirstDatabase?retryWrites=true&w=majority

I have replaced with the password for user "behai" in MongoDB Atlas. and I store it as MONGO_CONNECTION_STRING in my keys.py file.

I connect as:

import pymongo
import keys

client = pymongo.MongoClient( keys.MONGO_CONNECTION_STRING )

And I have the error:

ConfigurationError: All nameservers failed to answer the query cluster0.71o6u.mongodb.net. IN TXT: Server 192.168.0.1 UDP port 53 answered DNS message is malformed.

If I dropped "+srv" from the connection string, I could connect, but later accesses such as creating a database, creating a collection then inserting into the collection would result in an error:

ServerSelectionTimeoutError: cluster0.71o6u.mongodb.net:27017: [Errno 11001] getaddrinfo failed, Timeout: 30s, Topology Description: <TopologyDescription id: 61d8d475109bbda8e8b938f0, topology_type: Unknown, servers: [<ServerDescription ('cluster0.71o6u.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('cluster0.71o6u.mongodb.net:27017: [Errno 11001] getaddrinfo failed')>]>

When I try to ping cluster0.71o6u.mongodb.net:

C:\>ping cluster0.71o6u.mongodb.net

I would get this response:

Ping request could not find host cluster0.71o6u.mongodb.net. Please check the name and try again.

Does it seem that host " cluster0.71o6u.mongodb.net " does not exist?

But when I look into my MongoDB Atlas windows, I can see I have made 6 connections during the last 99 hours.

Try installing dnspython / pymongo[srv] <- (includes the dnspython) using pip and add the srv extra back.

import pymongo
    
db = pymongo.MongoClient("mongodb+srv://behai:<password>@cluster0.71o6u.mongodb.net/myFirstDatabase?retryWrites=true&w=majority")

Happy coding!

If you are using Pycharm go setting Project:YOURPROJECT and check if dnspython is there if not then click + icon and seach dnspython and install it.

When i tried to install on command line it keep saying its already installed but didnt work. This will probably solve your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM