Mongodb/atlas docker container - cannot connect using a URI that contains the db name

I’m using the mongodb/atlas:latest container image for spinning up a local mongo db instance for development. The container starts fine, but when if i try to connect using a mongodb uri that contains a db name (that exists on the db already) i receive a MongoServerError: Authentication failed. error

here are the details about my scenario:
I have the following docker-compose.yaml:

services:
  mongo:
    image: mongodb/atlas
    privileged: true
    command: |
      /bin/bash -c "atlas deployments setup --type local --port 27017 --bindIpAll --mdbVersion 6.0 --username root --password root --force && tail -f /dev/null"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    ports:
      - 27017:27017

In one terminal I am running docker-compose up
in another terminal i am able to connect to the database using the following command mongodb://root:root@localhost:27017/?directConnection=true - this work fine!
then i create a db named “some_test_db” with an example collection in it with the following commands

use 'some_test_db';
db.getCollections('col').insertOne({'test':'test'});

^this works fine too

but, in a third terminal, if i try to connect to the following db uri mongodb://root:root@localhost:27017/some_test_db?directConnection=true
i get an error:

MongoServerError: Authentication failed.

So in summary authentication works fine if i connect without a db parameter in the mongodb URI. Even switching to the db works after logging in with the root user/password. But the connection fails to authentication if the db name is in the URI.

Any help would be appreciated, please let me know if you need other details.

Hi @Nicholas_Pisani

The manual specifies the database in the uri is the default authentication database.

I recall this being referred to as the default database in the past and adding the parameter authSource=admin to the connection string results in the behaviour you are expecting.

1 Like

that did the trick! thanks Chris

for anyone else who finds this thread useful, here is the URI that allowed for successful authentication:

mongodb://root:root@localhost:27017/some_test_db?directConnection=true&authSource=admin