mongodb Pymongo错误,无效文档:从文件读取时无法对对象进行编码

ehxuflar  于 2022-11-28  发布在  Go
关注(0)|答案(1)|浏览(98)

我有一个csv文件,其中有一个标题行和100k个条目。
我在pycharm IDE中使用python,并将conda作为python解释器。condapymongo-3.4.0作为mongo-driver提供。
我解析我的csv文件并将其保存为磁盘上的jsonn文件,然后迭代json文件以将json对象插入mongo数据库。
JSON如下所示:

{
  a1 : {'name': 702104534, type='Single' }
  a2 : {'name': 702104535, type='Single' }
  a3 : {'name': 702104536, type='Married' }
}

Python代码:

import pymongo
import pickle

with open('my_json_file.json', 'rb') as in_file:
    person_json = pickle.load(in_file)

conn = pymongo.MonogClient('localhost','27017')
db = conn['db']
coll = db['coll']

persons = person_json.keys()
for person in persons:
    coll.insert_one(person_json[person])

通过以下错误:

Traceback (most recent call last):
File "C:/PyCharmWorkSpace/LCR/json2mongo.py", line 109, in <module>
    data2mongo()
File "C:/PyCharmWorkSpace/LCR/json2mongo.py", line 89, in data2mongo
    coll.insert_one(json_str)
File "C:\Anaconda3\lib\site-packages\pymongo\collection.py", line 657, in insert_one
    bypass_doc_val=bypass_document_validation),
File "C:\Anaconda3\lib\site-packages\pymongo\collection.py", line 562, in _insert
    check_keys, manipulate, write_concern, op_id, bypass_doc_val)
File "C:\Anaconda3\lib\site-packages\pymongo\collection.py", line 543, in _insert_one
    check_keys=check_keys)
File "C:\Anaconda3\lib\site-packages\pymongo\pool.py", line 424, in command
    self._raise_connection_failure(error)
File "C:\Anaconda3\lib\site-packages\pymongo\pool.py", line 552, in _raise_connection_failure
    raise error
File "C:\Anaconda3\lib\site-packages\pymongo\pool.py", line 419, in command
    collation=collation)
File "C:\Anaconda3\lib\site-packages\pymongo\network.py", line 94, in command
    None, codec_options, check_keys)
bson.errors.InvalidDocument: Cannot encode object: 702104534

但是,如果json字符串是一个变量,则同样可以工作。
Python代码:

import pymongo

conn = pymongo.MonogClient('localhost','27017')
db = conn['db']
coll = db['coll']

person = {'name': 702104534, 'type'='Single' }
coll.insert_one(person)

谢谢你的帮助。

jgovgodb

jgovgodb1#

json是动态生成的或从基于磁盘的文件中读取时,pymongo似乎存在一些运行时类型转换兼容性问题,当json字符串使用插入方法(如insertinsert_oneinsert_many)a插入 * 到mongodb时。
我能够通过关联标准python类型转换将json对象插入到mongodb中。

相关问题