简体   繁体   中英

Problems importing Json file into mongodb using python

Could anyone help me out with the following problem? I have been struggling with this problem for days... I have to import json files into mongodb using python. I tried both insert_many and insert_one but I get errors with the following code:

import json
import pymongo
from pymongo import MongoClient


mng_client = pymongo.MongoClient('localhost', 27017)
mng_db = mng_client['mydatabase1']
collection_credits = mng_db['credits']

with open('credits.json') as f:
    file_data = json.load(f)
    collection_credits.insert_many(file_data)

client.close()

error message: document must be an instance of dict, bson.son.SON...

and with:

import json
import pymongo
from pymongo import MongoClient


mng_client = pymongo.MongoClient('localhost', 27017)
mng_db = mng_client['mydatabase1']
collection_credits = mng_db['credits']

with open('credits.json') as f:
    file_data = json.load(f)
    collection_credits.insert_one(file_data)

client.close()

error: BSON document too large (191071260 bytes)

insert_many requires an iterable (eg a list), insert_one takes a single record.

Use insert_many if your data looks like this:

[ {
  "a": "1"
} ]

Use insert_one if your data looks like this:

{
  "a": "1"
}

As for the other error, mongodb documents have 16MB file size limit. You will need to pre-process the file to reduce the document size.

另请查看[mongoimport][1]可以直接导入 JSON 数据。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM