yonik
yonik

Reputation: 21

Mongodb pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused, Timeout: 30s,

I am trying to locally connect to my db. I've established a connection to the database on MongoDB Compass, but when I run my simple code, I get this error:

pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused, Timeout: 30s, Topology Description: <TopologyDescription id: 60e2b31fab1da2bb146bb38c, topology_type: Single, servers: [<ServerDescription ('localhost', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('localhost:27017: [Errno 111] Connection refused')>]> root@LAPTOP-8OKVP35I:/portfolio/myProjects/webDevelopment/shopify_db#

This is the code I am running:

import pymongo
from pymongo import MongoClient

client = pymongo.MongoClient()
db = client["Shopper_Info"]
my_collection = db["Names"]
shopper_data = {'name': 'Yoni', 'email': '[email protected]'}

my_collection.insert_one(shopper_data)

results= collection.find({"name": 'Yoni'})

for result in results:
print(result)

Upvotes: 2

Views: 17574

Answers (3)

Shiv Sharan Kumar
Shiv Sharan Kumar

Reputation: 11

just add the above code to your settings.py in django :-

DATABASE = {
'default': {
'ENGINE': 'djongo',
 "CLIENT": {
           "name": <your_database_name>,
           "host": <your_connection_string>,
           "username": <your_database_username>,
           "password": <your_database_password>,
           "authMechanism": "SCRAM-SHA-1",
        },
    }
}

but in host you may get this issue :-"pymongo.errors.ServerSelectionTimeoutError:"[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997) so for this you add like :- "mongodb+srv://sampleUser:[email protected]/sampleDB??ssl=true&ssl_cert_reqs=CERT_NONE&retryWrites=true&w=majority"

Upvotes: 1

Doddi girish
Doddi girish

Reputation: 115

This happend to me as well. make sure that you have started the mongod server.that worked for me.

sudo service mongod start.

Upvotes: 1

ARITRA GHOSH
ARITRA GHOSH

Reputation: 59

This problem was also happening in my stack, I had my connection string in an env file to connect to mongo atlas.

MONGO_URI=mongodb://<username>:<password>@cluster-details

But the right way to do this is

MONGO_URI="mongodb://<username>:<password>@cluster-details"

Upvotes: 2

Related Questions