MongoDB shell version v5.0.2
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Error: couldn’t connect to server 127.0.0.1:27017, connection attempt failed: SocketException: Error connecting to 127.0.0.1:27017 :: caused by :: Connection refused :
Is your mongodb server up and running on port 27017?
Was it installed as service?
What does status of service show
Are you trying to connect locally or remotely
Looking at the prerm script for mongodb-server(/var/lib/dpkg/info/mongodb-server.prerm) it might not be shutting down mongod on the apt autoremove if you are using systemd. You can check that with pidof mongod, pgrep mongod or whatever other method you can think of. So a safety step might be systemctl stop mongodb before the removal/purge steps.
If you have got a mix of ubuntu repo and mongodb-org:
If your output includes a mix of mongodb-org and mongodb binaries, you may need to first apt remove, apt purge, and apt autoremove the mongodb-org package before attempting to remove and purge the Ubuntu mongodb package. After clearing all MongoDB-related packages, retry the installation procedure.