我正在尝试编写一个 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 插入重复用户?谢谢!