我有一个csv
文件,其中有一个标题行和100k个条目。
我在pycharm
IDE中使用python
,并将conda
作为python解释器。conda
将pymongo-3.4.0
作为mongo-driver
提供。
我解析我的csv
文件并将其保存为磁盘上的json
n文件,然后迭代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)
谢谢你的帮助。
1条答案
按热度按时间jgovgodb1#
当
json
是动态生成的或从基于磁盘的文件中读取时,pymongo
似乎存在一些运行时类型转换兼容性问题,当json
字符串使用插入方法(如insert
、insert_one
或insert_many
)a插入 * 到mongodb
时。我能够通过关联标准python类型转换将
json
对象插入到mongodb
中。