【问题标题】:Cannot insert into mongo db with python无法使用python插入mongodb
【发布时间】:2018-03-20 20:20:36
【问题描述】:

我在 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 中不起作用。我怎样才能让它工作?

【问题讨论】:

    标签: python database mongodb mlab


    【解决方案1】:

    问题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)
    

    【讨论】:

      【解决方案2】:

      虽然 tuan huynh 的回答并没有完全解决我的问题,但我尝试了一下,它帮助我找到了解决方案:

      从 pymongo 导入 MongoClient

      URI和以前一样,我只是说

      db = client.<db-name>
      posts = db.<collection-name>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-12-22
        • 2012-02-07
        • 1970-01-01
        • 2016-04-04
        • 1970-01-01
        • 2019-03-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多