'Unauthorized' error when connecting to MongoDB using Springboot application

Hello All,

I had an application which was communicating with my database properly and without any problem. But when I set a password for the database, it stopped working.
Now, I get

Query failed with error code 13 with name ‘Unauthorized’

error when I run my Springboot apllication.
However, using the shell, I can connect to the database, see the collections, etc.
My MongoDB version is 4.2.0 and I run this command to connect to the database in my shell:

mongo --port 27017 -u “myUsername” -p “myPassword” --authenticationDatabase “admin”

In my Springboot application I have the following URI:

data:
mongodb:
uri: mongodb://myUsername:myPassword@localhost:27017/mainDatabase?authSource=admin&retryWrites=true&w=majority

But it doesn’t work.
Can anyone help me please?

If it works with shell it should work with your application too.
Can you connect from shell using the exact connect string from your uri?
What is mainDatabase?Is it actual name redacted
Make sure name is matching with that from show dbs

For anyone who faces the same problem in the future.
I had actually exactly the same settings (passwords, username, etc.) on the local and on the server but it didn’t work. Finally, I updated my MongoDB to the latest version (1.6) and my Spring Boot Application to the latest version (2.7.4 I think) and it worked!