1

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': 'test@gmail.com'}

my_collection.insert_one(shopper_data)

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

for result in results:
print(result)
Nebulastic
  • 7,845
  • 2
  • 31
  • 56
yonik
  • 11
  • 1
  • 2
  • What is the connection string you use for the connection via Compass? – Michael Ruth Jul 05 '21 at 07:35
  • mongodb://localhost:27017 – yonik Jul 05 '21 at 07:44
  • Does this answer your question? [Pymongo keeps refusing the connection at 27017](https://stackoverflow.com/questions/7744147/pymongo-keeps-refusing-the-connection-at-27017) – Michael Ruth Jul 05 '21 at 07:53
  • Well no, because when I run those commands involving /var/lib/mongodb.lock it says no such file or directory. When attempting to restart the service with their command, it says no service found – yonik Jul 05 '21 at 08:05
  • That solution is platform-dependent, but the generic process is the same: clean up lock file, restart mongod. Which platform are you running this on and how do you normally start mongod? – Michael Ruth Jul 05 '21 at 08:19
  • Using Ubuntu. I start Mogod by opening the application (MongoDB Compass) – yonik Jul 05 '21 at 08:22
  • MongoDB Compass is a client, not a server, it does not start the server, it merely connects to it. This solution suggests restarting the server, which on Ubuntu should be the `mongod` process and can be found with the command `ps aux | grep mongod` – Michael Ruth Jul 05 '21 at 08:28
  • Understood. I ran that command and then ran the file. Still got the same error – yonik Jul 05 '21 at 08:31

2 Answers2

2

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"
1

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

sudo service mongod start.