通过Python向MongoDB添加用户

14 投票
2 回答
15026 浏览
提问于 2025-04-18 12:52

我想在MongoDB中添加用户,这样我们就可以自动化安装MongoDB,并且在安装时就已经设置好身份验证。我可以成功地使用pymongo添加只读用户或数据库拥有者,方法是:

from pymongo import MongoClient

client = MongoClient('localhost:27017')   
client.admin.authenticate('siteRootAdmin', 'Test123')
client.testdb.add_user('newTestUser', 'Test123', True)

但是当我使用下面的代码块来指定角色时,它就失败了:

from pymongo import MongoClient

client = MongoClient('localhost:27017')
client.admin.authenticate('siteRootAdmin', 'Test123')
client.testdb.add_user('newTestUser', 'Test123', False, 'readWrite')

并且出现了这个错误:

line 10, in <module>
    client.admin.add_user('newTestUser', 'Test123', False, 'readWrite')
TypeError: add_user() takes at most 4 arguments (5 given)

在文档中提到,你可以为用户文档添加一些可选字段,比如其他角色。有没有人能够正确设置这些角色?具体来说,我想要一些可以向集合中添加数据的读写服务账户,但不想给他们完全的数据库拥有者权限。

2 个回答

13

从版本3开始,add_user这个功能被标记为不推荐使用,以后会被移除。如果你调用这个功能,会出现以下警告:

DeprecationWarning: add_user is deprecated and will be removed in PyMongo 4.0. Use db.command with createUser or updateUser instead

上面的代码可以改写成

client.testdb.command(
    'createUser', 'newTestUser', 
    pwd='Test123',
    roles=[{'role': 'readWrite', 'db': 'testdb'}]
)

14

这里有个解决办法:

client.testdb.add_user('newTestUser', 'Test123', roles=[{'role':'readWrite','db':'testdb'}])

注意:因为你要设置“角色”,所以第三个参数(只读)要留空。

撰写回答