gpt4 book ai didi

python - 为什么我在尝试通过 python 插入数据 MongoDB 时遇到错误?

转载 作者:太空宇宙 更新时间:2023-11-03 21:18:56 25 4
gpt4 key购买 nike

我正在尝试通过 python 将数据从 Exasol 移动到 MongoDB。但我被困在某个地方。我是 Python 新手,实际上这是我的第一个代码。当我尝试插入数据时出现错误。你能帮我一下吗?

while x < len(Read):
col = Read[x]
while y < len(Col_Names):
column_name = "'" + Col_Names[y] + "'"
if col[y].isnumeric() or re.match("^\d+?\.\d+?$", col[y]):
column_value = col[y]
else:
column_value = "'" + col[y] + "'"
field = column_name + " : " + column_value
data.append(field)
doc = str(data)[1:-1]
document = "{" + doc + "}"
y += 1
for char in '"':
document = document.replace(char,'')
print(document)
result = db.nyc.insert_one(document)
print('Created {0} of 100 as {1}'.format(x,result.inserted_id))
y = 0
x += 1

打印结果(文档)

    {
'VENDOR_ID': 'CMT',
'PICKUP_DATETIME': '2014-01-09 20:45:25.000000',
'DROPOFF_DATETIME': '2014-01-09 20:52:31.000000',
'PASSENGER_COUNT': 1,
'TRIP_DISTANCE': 0.7,
'PICKUP_LONGITUDE': '-73.99477',
'PICKUP_LATITUDE': 40.736828,
'RATE_CODE': 1,
'STORE_AND_FWD_FLAG': 'N',
'DROPOFF_LONGITUDE': '-73.982227',
'DROPOFF_LATITUDE': 40.73179,
'PAYMENT_TYPE': 'CRD',
'FARE_AMOUNT': 6.5,
'SURCHARGE': 0.5,
'MTA_TAX': 0.5,
'TIP_AMOUNT': 1.4,
'TOLLS_AMOUNT': 0,
'TOTAL_AMOUNT': 8.9,
'COUNTER': 1,
'PATH_ID': 1
}

错误消息

Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python36\exasol_to_mongodb.py", line 48, in <module>
result = db.nyc.insert_one(document)
File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\pymongo\collection.py", line 684, in insert_one
common.validate_is_document_type("document", document)
File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\pymongo\common.py", line 453, in validate_is_document_type
"collections.MutableMapping" % (option,))
TypeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a type that inherits from collections.MutableMapping

最佳答案

您将文档存储为字符串,而不是字典。 print(type(document)) 应该返回字符串。

您应该将数据放入实际的字典中,而不是手动“模拟”字典格式:

for col in Read:
document = dict()
while y < len(Col_Names):
document[Col_Names[y]] = col[y]
result = db.nyc.insert_one(document)

希望能帮到你!

关于python - 为什么我在尝试通过 python 插入数据 MongoDB 时遇到错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54463546/

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