pymongo 2.8 - 如何避免在管理数据库中插入重复用户

pymongo 2.8 - how to avoid inserting duplicate user in admin db

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

根据 pymongo 文档

Will change the password if user name already exists.

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