通过python将用户添加到mongodb [英] add user to mongodb via python

查看:177
本文介绍了通过python将用户添加到mongodb的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够将用户添加到MongoDB,以便我们可以使用已加入身份验证的方式自动执行MongoDB安装.通过执行以下操作,我可以使用pymongo成功添加用户,这些用户是只读用户或dbOwner:

I want to be able to add users to MongoDB so that we can automate MongoDB installs with authentication already baked in. I can successfully add users using pymongo that are read only or are dbOwner by doing this:

from pymongo import MongoClient

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

但是当我执行以下代码块来指定角色时,它将失败:

but when I do this following code block to specify roles, it fails:

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)

在文档中,这意味着您能够为用户文档提供可选字段,例如其他角色.有人能正确设置这些吗?即,我想拥有可以将数据添加到集合但没有完整的dbOwner特权的readWrite服务帐户.

In the docs it implies that you are able to have optional fields for the user document such as other roles. Has anyone been able to set these correctly? Namely, I want to have readWrite service accounts that can add data to collections but don't have full dbOwner privileges.

推荐答案

以下是解决方法:

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

注意:当您要设置角色"时,应将第3个参数(只读)保留为空.

Note: as you're going to set "roles", should leave the 3rd argument (read_only) empty.

这篇关于通过python将用户添加到mongodb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆