pymongo.errors.ServerSelectionTimeoutError:localhost:27017:[WinError 10061] No connection could be made because the target machine actively refused it
Asked Answered
P

6

9

I am following the Python tutorial from W3Schools. I just started the MongoDB chapter. I installed MongoDB and checked it with:

import pymongo

without getting an error.

But as soon as I enter the following code:

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mydict = { "name": "John", "address": "Highway 37" }

x = mycol.insert_one(mydict)

print(x.inserted_id)

I get these messages and an error message at the bottom in cmd:

cd C:\Users\xxx\myname
python index.py

Output:

Traceback (most recent call last):
  File "index.py", line 8, in <module>
    x = mycol.insert_one(mydict)
  File "C:\Users\path...\pymongo\collection.py", line 695, in insert_one
    self._insert(document,
  File "C:\Users\path...\pymongo\collection.py", line 610, in _insert
    return self._insert_one(
  File "C:\Users\path...\pymongo\collection.py", line 599, in _insert_one
    self.__database.client._retryable_write(
  File "C:\Users\path...\pymongo\mongo_client.py", line 1490, in _retryable_write
    with self._tmp_session(session) as s:
  File "C:\Program Files\WindowsApps\path...\lib\contextlib.py", line 113, in __enter__
    return next(self.gen)
  File "C:\Users\path...\pymongo\mongo_client.py", line 1823, in _tmp_session
    s = self._ensure_session(session)
  File "C:\Users\path...\pymongo\mongo_client.py", line 1810, in _ensure_session
    return self.__start_session(True, causal_consistency=False)
  File "C:\Users\path...\pymongo\mongo_client.py", line 1763, in __start_session
    server_session = self._get_server_session()
  File "C:\Users\path...\pymongo\mongo_client.py", line 1796, in _get_server_session
    return self._topology.get_server_session()
  File "C:\Users\path...\pymongo\topology.py", line 482, in get_server_session
    self._select_servers_loop(
  File "C:\Users\path...\pymongo\topology.py", line 208, in _select_servers_loop
    raise ServerSelectionTimeoutError(
pymongo.errors.ServerSelectionTimeoutError: localhost: 27017: [WinError 10061] Could not connect because target computer actively refused connection

I also tried too disabling firewall temporarily, but the error kept coming up.

I used:

"python 3.8.2
, mongoDB 4.2.5.0
, pymongo 3.10.1
, windows 10 home"

What is going wrong?

Pennsylvania answered 24/3, 2020 at 21:15 Comment(7)
Is your mongod service running and can you access the mongo shell?Evanish
import pymongo only loads the library - it doesn't check mongo is running.Magnitude
@Belly Buster These are the first steps of this chapter. Because I did not receive an error message, I know that mongoDB has been successfully installed. w3schools.com/python/python_mongodb_query.aspPennsylvania
@Evanish I have installed the community version. MongoDB shell is only included with the enterprice version.Pennsylvania
I have now added some more information in my questionPennsylvania
@Pennsylvania - The mongo shell is included with the community edition. Did you follow the mongodb install instructions for your OS and verify that it is running correctly? Your error connection refused will result if the mongod service is not running (it needs to be listening on 27017 the default port unless you specify a different one).Evanish
@Evanish I am an absolute noob with using cmd and using databases. I had not yet installed mongoDB but it is now done. Thank you all for thinking along! I can continue with my studies.Pennsylvania
M
11

There is nothing wrong with your code.

If you have disabled your firewall, the most likely reason is that the MongoDB service is not installed or running. On Windows, press the Windows key and type services to open the services application. Check the service MongoDB Server is listed and has a Running status.

You can test local connectivity by opening your favourite Windows terminal or PowerShell and typing mongo. If it is working you should see:

PS> mongo
MongoDB shell version v4.2.3
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("1b5499b8-166a-4de6-a8c9-643499f04e66") }
MongoDB server version: 4.2.3
Magnitude answered 25/3, 2020 at 12:39 Comment(0)
E
1

Try running this command in CLI:

mongod

If you see any error, then watch the video How to Install MongoDB on Windows 10. This video was helpful.

Epos answered 22/5, 2021 at 14:3 Comment(0)
C
0

I was trying to connect from Django. I am using Python 3.7 and earlier tried with the URI string provided for Python 3.6+, but it didn't work in PyCharm or Jupyter. But later I chose the URI string for Python version 3.4+ and it worked in Jupyter Notebook, but I got an issue connecting from the Django project.

So to solve this I installed MongoDB application from https://fastdl.mongodb.org/win32/mongodb-win32-x86_64-2012plus-4.2.11-signed.msi which started MongoDB services on my machine. And without changing any previous code I am able to connect. Below is my code to connect to MongoDB from Django application:

DATABASES = {
    'default': {
        'ENGINE': 'djongo',
        'NAME': <DBname>,
        'HOST': "mongodb://<username>:<password>@cluster0-shard-00-00.pifkd.mongodb.net:27017,cluster0-shard-00-01.pifkd.mongodb.net:27017,cluster0-shard-00-02.pifkd.mongodb.net:27017/<DBname>?ssl=true&replicaSet=atlas-79xyw7-shard-0&authSource=admin&retryWrites=true&w=majority",
        'USER': <username>,
        'PASSWORD': <password>,
    }
}
Colettecoleus answered 17/1, 2021 at 19:9 Comment(0)
C
0

In my case I put the wrong port in

client = pymongo.MongoClient('mongodb://localhost:27017/')

You can check which port MongoDB server is listening to (in Windows) via Task ManagerPerformanceOpen Resource MonitorNetworkListening Ports

And search for mongod.exe.

Codd answered 11/4, 2022 at 0:17 Comment(0)
C
0

Your device might have disabled the MongoDB services.

Search services in the search bar and find MongoDB services in the list. First right and then click on Properties and change from either Disable to Automatic or Manual to Automatic.

In case you want to keep it Manual, click on start after right-clicking the MongoDB services option in the list.

Chromate answered 10/2, 2023 at 10:49 Comment(0)
P
0

I solved it by uninstalling my antivirus. Now I am terrified of navigating across the web, but I'll just be careful until my classes end in June. In the mean time, my antivirus was blocking any communication with MongoDB. Now I can import it via Jupyter Notebook and it works fine.

Pernod answered 13/3 at 4:13 Comment(1)
You should not need to disable the antivirus, it should have options to allow things like this. I feel this is dangerous advice, use with caution.Harpsichord

© 2022 - 2024 — McMap. All rights reserved.