0

我正在尝试编写一个 Python 脚本来使用 pymongo 2.8 将用户添加到 MongoDB。这是我的代码:

db = conn['test123']
collection=db['testing']
db1 = conn['admin']
try:
    data = db1.add_user('test123user', 'test123pass', roles=[{'role':'readWrite','db':'test123'}])
    print("Database with user  is created")
except Exception as e:
    print("error: Unable to create the user for database ")
    raise

当我多次运行相同的代码时,我看不到任何错误,就像我们在插入重复用户时在 mongo shell 上看到的那样:

2017-01-06T17:29:59.209-0500 E QUERY    [thread1] Error: couldn't add user: User "db09user@admin" already exists 

如何避免通过 pymomgo 插入重复用户?谢谢!

4

1 回答 1

0

根据 pymongo 文档

如果用户名已经存在,将更改密码。

这意味着如果用户已经创建,则您不会使用此脚本创建新用户。所以不存在重复问题。

于 2017-01-06T23:24:04.590 回答