Mongo client connects with command-line params, but fails with equivalent URI

mongodb

When I create a MongoDB database with this script:

#!/bin/bash

javascript='
db.dropUser("admin");
db.createUser({
    user: "admin",
    pwd: "password",
    roles: [
        {role: "userAdminAnyDatabase", db: "admin"}
    ]
});
db.getSiblingDB("example").empty.save({"empty": 0});
'

docker-compose exec mongodb mongo --eval "${javascript}"

I can successfully login with the mongo shell and command-line parameters:

$ mongo --host docker-machine -u admin -p password
MongoDB shell version v3.4.10
connecting to: mongodb://docker-machine:27017/
MongoDB server version: 3.4.10

But with what seems like the equivalent connection URI, the connection fails:

$ mongo 'mongodb://admin:password@docker-machine/'
MongoDB shell version v3.4.10
connecting to: mongodb://admin:password@docker-machine/
2017-12-06T21:17:47.297-0700 E QUERY    [thread1] Error: Authentication failed. :
connect@src/mongo/shell/mongo.js:237:13
@(connect):1:6
exception: connect failed

And the MongoDB log shows:

2017-12-07T04:16:27.703+0000 I ACCESS   [conn100]
    SCRAM-SHA-1 authentication failed for admin on admin from client
    10.211.55.2:52496 ; AuthenticationFailed: SCRAM-SHA-1 authentication
    failed, storedKey mismatch

What's going on?

Best Answer

You need to connect to the MongoDB admin database:

docker-compose exec mongodb mongo admin --eval "${javascript}"
#                                 ^^^^^ add this
Related Topic