I post here as a follow up of Econnrefused ::1:27017 as it is no longer possible to post replies there.
When connecting to mongodb with MongoClient i get
MongoServerSelectionError: connect ECONNREFUSED ::1:27017 when connecting to ‘mongodb://localhost:27017/’ but no error when connecting to ‘mongodb://127.0.0.1:27017/’.
As @Stennie mention the problem is that MongoClient tries to connect with IPv6. It didn’t seem to me it could be that because in my /etc/hosts file localhost is configured for both IPv4 and IPv6:
127.0.0.1 localhost 255.255.255.255 broadcasthost ::1 localhost
But with that configuration it seems that localhost will randomly redirect to IPv4 or v6, so the solution is to remove the line for IPv6.