我有一个csv
文件,其中包含标题行和100k条目。
我在python
IDE和pycharm
中使用conda
作为python解释器。 conda
将pymongo-3.4.0
视为mongo-driver
。
我解析我的csv
文件并将其保存为磁盘上的json
n文件,然后遍历json
文件以在{{{{}}中插入json
个对象1}}数据库。
JSON看起来像这样:
mongo
Python代码:
{
a1 : {'name': 702104534, type='Single' }
a2 : {'name': 702104535, type='Single' }
a3 : {'name': 702104536, type='Married' }
}
通过以下错误:
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])
但是,如果json字符串是变量
,同样有效Python代码:
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
感谢您的帮助。
答案 0 :(得分:0)
当pymongo
字符串为json在动态生成或从基于磁盘的文件中读取json
时,mongodb
会出现一些运行时类型转换兼容性问题>使用插入方法插入到insert
,例如insert_one
或insert_many
或json
。
通过关联标准python类型转换,我能够将mongodb
对象插入<div *ngFor="let post of objectKeys(_postArrayMatch.team1)">
<div> Team1: {{ _postArrayMatch.team1[post]}}</div>
</div>
。