为什么在尝试通过python插入数据MongoDB时出现错误?

时间:2019-01-31 15:08:49

标签: python mongodb

我正在尝试通过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

1 个答案:

答案 0 :(得分:0)

您将document存储为字符串而不是字典。 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)

希望我能帮上忙!