我正在mlab上托管一个mongo数据库,我有一个非常简单的程序可以将文档插入到现有的集合中。插件在JS中适用于我,但由于某些原因不适用于Python。这就是它在Python中的样子:
from pymongo import MongoClient
client = MongoClient('mongodb://<user>:<password>@<address>/<db-name>')
db = client.congresspersons
posts = db.posts
post_data = {
'title': 'Python and MongoDB',
'content': 'PyMongo is fun, you guys',
'author': 'Scott'
}
result = posts.insert_one(post_data)
此代码主要来自here。
但是,我一直收到这个错误:
pymongo.errors.OperationFailure: not authorized on config to execute command { insert: "congresspersons.posts", ordered: true, documents: [ { content: "PyMongo is fun, you guys", _id: ObjectId('5ab16ae3626b6217f7c2a079'), author: "Scott", title: "Python and MongoDB" } ] }
这些是用户的权限:
{
...
"roles": [
{
"role": "dbOwner",
...
}
]
}
我不明白为什么这样的简单插入在Python中不起作用。我怎样才能让它发挥作用?
答案 0 :(得分:0)
问题db = client.congresspersons
,您可以尝试使用此代码
client = MongoClient('mongodb://<user>:<password>@<address>')
db = client['<db-name>']
posts = db['posts_name']
post_data = {
'title': 'Python and MongoDB',
'content': 'PyMongo is fun, you guys',
'author': 'Scott'
}
result = posts.insert_one(post_data)
答案 1 :(得分:0)
虽然tuan huynh的答案并没有完全解决我的问题,但我还是玩弄它并帮助我找到解决方案:
来自pymongo import MongoClient
URI与以前保持一致,我只想说
db = client.<db-name>
posts = db.<collection-name>