gpt4 book ai didi

python - 使用python向mongodb中插入数据

转载 作者:行者123 更新时间:2023-12-01 03:48:08 24 4
gpt4 key购买 nike

这是我第一次尝试使用数据库,但我在基础知识方面遇到了一些问题。尝试在网上查找但找不到简单问题的答案。当我尝试向数据库添加一些信息时,出现一大堆错误。

import pymongo


def get_db():
from pymongo import MongoClient
client = MongoClient("mongodb://xxxxxx:xxxxxx@ds029735.mlab.com:29735/xxxxxxx")
db = client.myDB
return db

def add_country(db):
db.countries.insert({"name": "Canada"})

def get_country(db):
return db.contries.find_one()

db = get_db()
add_country(db)

我收到此错误消息:

File "/Users/vincentfortin/Desktop/Python_code/mongo.py", line 21, in <module>
add_country(db)
File "/Users/vincentfortin/Desktop/Python_code/mongo.py", line 11, in add_country
db.countries.insert({"name": "Canada"})
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymongo/collection.py", line 2212, in insert
check_keys, manipulate, write_concern)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymongo/collection.py", line 535, in _insert
check_keys, manipulate, write_concern, op_id, bypass_doc_val)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymongo/collection.py", line 516, in _insert_one
check_keys=check_keys)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymongo/pool.py", line 239, in command
read_concern)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymongo/network.py", line 102, in command
helpers._check_command_response(response_doc, None, allowable_errors)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymongo/helpers.py", line 205, in _check_command_response
raise OperationFailure(msg % errmsg, code, response)
pymongo.errors.OperationFailure: not authorized on myDB to execute command { insert: "countries", ordered: true, documents: [ { _id: ObjectId('579a6c6ed51bef1274162ff4'), name: "Canada" } ] }

最佳答案

  1. 检查两次 ds029735.mlab.com:29735/xxxxxxx 中的 xxxxxxx 是否等于 中的 myDB db = client.myDB 。我的意思是,如果您的连接字符串是 mongodb://username:password@ds029735.mlab.com:29735/xyz 那么您的代码应该是 db = client.xyz 而不是db = client.zyx(或其他名称)。

  2. 如果您的用户是只读用户,请检查 mLab 控制面板 /image/UIRr2.png

这两个问题都会返回像您一样的错误,所以我不知道您遇到的是哪一个。

关于python - 使用python向mongodb中插入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38646338/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com