I am hosting a mongo database on mlab , and I have an extremely simple program to insert a document into an existing collection. Insertion works for me in JS but not in Python for some reason. This is what it looks like in 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)
This code mostly came from here .
However, I keep getting this error:
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" } ] }
These are the permissions for the user:
{
...
"roles": [
{
"role": "dbOwner",
...
}
]
}
I don't understand why such simple insertion is not working in Python. How can I get this to work?
Problem db = client.congresspersons
, You can try this code
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)
Although tuan huynh's answer didn't exactly solve my problem, I played around with it and it helped me reach the solution:
from pymongo import MongoClient
The URI stays the same as before, I just say
db = client.<db-name>
posts = db.<collection-name>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.