(Py)Mongo 可以远程连接,但本地连接时未授权

(Py)Mongo can connect remotely but unauthorised when connecting locally

我在 Digital Ocean droplet 上有一个 MongoDB 实例。我可以使用 PyMongo 和 Compass 远程进入它,但是通过 PyMongo 本地连接告诉我我没有被授权。

Authentication failed., full error: {'ok': 0.0, 'errmsg': 'Authentication failed.', 'code': 18, 'codeName': 'AuthenticationFailed'}

角色

[
{
    "_id" : "admin.normaluser",
    "userId" : ...,
    "user" : "normaluser",
    "db" : "admin",
    "roles" : [
        {
            "role" : "readWrite",
            "db" : "greedymercs"
        }
    ]
},
{
    "_id" : "admin.rootuser",
    "userId" : ...,
    "user" : "rootuser",
    "db" : "admin",
    "roles" : [
        {
            "role" : "root",
            "db" : "admin"
        }
    ]
}

]

我可以使用 mongodb://normaluser:<pass>@<ip>:27017/ 远程连接,但通过 mongodb://normaluser:<pass>@localhost:27017/ 本地连接失败。我尝试过使用默认数据库、rootuser 等,但每次都是同样的问题。

mongood.conf

# network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1,<public ip>

#security:
security:
  authorization: enabled

我用来测试本地连接的脚本

import os
import time

from pymongo import MongoClient

client = MongoClient(os.environ["MONGO_URI"])

now = time.time()

try:
    for i in range(100):
        client.greedymercs.mongoTest.insert_one({"number": i})

except Exception as e:
    print(e)

else:
    print("100 inserts:", time.time() - now)

now = time.time()

try:
    results = list(client.greedymercs.mongoTest.find({}))

except Exception as e:
    print(e)

else:
    print(f"Find all ({len(results)}):", time.time() - now)

添加了 ?authSource=admin 解决了问题 :)